1. 程式人生 > >2月9日 Time and Date(Ruby基礎)

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

and pad elsif adding bsp back new post gin


根據生日計算年齡。

定義一個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基礎)