Alex Rivera | Logout

Get person's age in Ruby

Asked 2009-05-04T08:27:12.677
138

I'd like to get a person's age from its birthday. now - birthday / 365 doesn't work, because some years have 366 days. I came up with the following code:

now = Date.today
year = now.year - birth_date.year

if (date+year.year) > now
  year = year - 1
end

Is there a more Ruby'ish way to calculate age?

Edit
Report

2 Answers

54

I've found this solution to work well and be readable for other people:

    age = Date.today.year - birthday.year
    age -= 1 if Date.today < birthday + age.years #for days before birthday

Easy and you don't need to worry about handling leap year and such.

answered 2009-05-04T13:50:37.593
4

I like this one:

now = Date.current
age = now.year - dob.year
age -= 1 if now.yday < dob.yday
answered 2012-02-03T14:35:03.433

Your Answer