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?
I think it's alot better to do not count months, because you can get exact day of a year by using
Time.zone.now.yday
.Use this:
I believe this is functionally equivalent to @philnash's answer, but IMO more easily understandable.
Usage:
This answer is the best, upvote it instead.
I like @philnash's solution, but the conditional could be compacter. What that boolean expression does is comparing [month, day] pairs using lexicographic order, so one could just use ruby's string comparison instead:
I've found this solution to work well and be readable for other people:
Easy and you don't need to worry about handling leap year and such.