Class: Date

Inherits:
Object
  • Object
show all
Defined in:
lib/date_age.rb

Instance Method Summary collapse

Instance Method Details

#ageObject

Return age of today



22
23
24
# File 'lib/date_age.rb', line 22

def age
  age_at(Date.today)
end

#age_at(date) ⇒ Object

Return age at specified ‘date`



6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/date_age.rb', line 6

def age_at(date)
  unless date.respond_to?(:year) && date.respond_to?(:month) && date.respond_to?(:day)
    raise ArgumentError, "age_at(date): date should respond to :year, :month and :day"
  end
  birthday = self
  today    = date
  age = today.year - birthday.year
  if today.month < birthday.month
    age -= 1
  elsif birthday.month == today.month
    age -= 1 if today.day < birthday.day
  end
  age
end