在Ruby中获取人的年龄 [英] Get person's age in Ruby
本文介绍了在Ruby中获取人的年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从生日中获取一个人的年龄.now -birthday/365
不起作用,因为有些年份有 366 天.我想出了以下代码:
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
是否有更像 Ruby 风格的方法来计算年龄?
Is there a more Ruby'ish way to calculate age?
推荐答案
我知道我在这里参加聚会迟到了,但是在尝试计算 2 月 29 日出生的人的年龄时,已接受的答案会崩溃闰年.这是因为对 birthday.to_date.change(:year => now.year)
的调用创建了一个无效的日期.
I know I'm late to the party here, but the accepted answer will break horribly when trying to work out the age of someone born on the 29th February on a leap year. This is because the call to birthday.to_date.change(:year => now.year)
creates an invalid date.
我改用以下代码:
require '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
这篇关于在Ruby中获取人的年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文