Get person’s age in Ruby

Get person’s age in Ruby

Asked on January 11, 2019 in Ruby on Rails.
Add Comment


  • 3 Answer(s)

    The call to birthday.to_date.change(:year => now.year) creates an invalid date.

    def age(dob)
       now = Time.now.utc.to_date
       now.year - dob.year - ((now.month > dob.month || (now.month == dob.month && now.day >= dob.day)) ? 0 : 1)
    end
    

    Answered on January 11, 2019.
    Add Comment

    Solution to work well and be readable,

    age = Date.today.year - birthday.year
    age -= 1 if Date.today < birthday + age.years #for days before birthday
    
    Answered on January 11, 2019.
    Add Comment

    Follow this command: 

    def age
      now = Time.now.utc.to_date
      now.year - birthday.year - (birthday.to_date.change(:year => now.year) > now ? 1 : 0)
    end
    

    Answered on January 11, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.