首页 > 其他 > 详细

2月9日 Time and Date(Ruby基础)

时间:2018-02-09 16:26:23      阅读:190      评论:0      收藏:0      [点我收藏+]


 

根据生日计算年龄。

定义一个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

 

2月9日 Time and Date(Ruby基础)

原文:https://www.cnblogs.com/chentianwei/p/8435844.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!