根据生日计算年龄。
定义一个Person类,内含初始化method, age method.
require "date"
class Person
attr_reader :birth_date
# 通过 Person.new 获取关键参数生年月日
def initialize(birth_date)
@birth_date = birth_date
end
# 返回某个日期的年龄。没有指定日期则返回今天的年龄。
def age(date=Date.today)
# 如果是出生前则返回 -1 (错误)
return -1 if date < birth_date
years = date.year - birth_date.year
if date.month < birth_date.month
# #没满一年,所以减一年
years -= 1
elsif date.month == birth_date.month && date.day < birth_date.day
# 还差不到一个月生日,所以减一年
years -= 1
end
return years
end
end
ruby = Person.new(Date.new(1993, 2, 24))
p ruby.birth_date # 生年月日
p ruby.age # 今天
p ruby.age(Date.new(2013, 2, 23)) # 20岁的前一天 19
p ruby.age(Date.new(2013, 2, 24)) # 20岁的生日 20
p ruby.age(Date.new(1988, 2, 24)) # 出生之前 -1