Calculate age in Ruby


 

Two examples of how you can calculate the number of full years a person is on a certain date. Includes unit testing. To run the tests just run ruby age.rb
Thanks to Alexey Verkhovsky and Paul Barry on the Ruby on Rails list for the unit tests.
Only the age_at was written by me.

# BirthdayTest
# jonelf ยค gmail.com
require 'test/unit'
class BirthdayTest < Test::Unit::TestCase

 def test_age_at_non_leap_year_with_leap_year_dob
   assert_equal 19, age_at(Date.new(2007, 3, 1), Date.new(1988, 3, 1))
 end

 def test_age_at_leap_year_with_non_leap_year_dob
   assert_equal 20, age_at(Date.new(2008, 2, 29), Date.new(1987, 3, 1))
 end

 def test_age_non_leap_year_with_leap_year_dob
   assert_equal 19, age(Date.new(2007, 3, 1), Date.new(1988, 3, 1))
 end

 def test_age_leap_year_with_non_leap_year_dob
   assert_equal 20, age(Date.new(2008, 2, 29), Date.new(1987, 3, 1))
 end

end

def age_at(date, dob)
  date.year - dob.year - ( date.month-dob.month < 0 ? 1 : date.day-dob.day < 0 ? 1:0 )
end

def age(now, birthdate)
 had_birthday_passed_this_year = (now.month * 100 + now.day >= birthdate.month * 100 + birthdate.day)
  if had_birthday_passed_this_year
    now.year - birthdate.year
  else
    now.year - birthdate.year - 1
  end
end