2

Possible Duplicate:
Get person's age in Ruby

I am very new to Ruby on Rails, and I have just created a small program to store people, using their names, dates of birth (dob), genders, etc. However, when I query the people from the database using @persons = Persons.find(:all), and I try to list them, I'd love to display their age, that is, today - persons.dob, rather than their date of birth proper.

Community
  • 1
  • 1
azinyue
  • 135
  • 2
  • 5

5 Answers5

7
today = Date.today
d = Date.new(today.year, dob.month, dob.day)
age = d.year - dob.year - (d > today ? 1 : 0)
Vadim
  • 17,897
  • 4
  • 38
  • 62
4
def age(dob)
  today = Date.today
  age = today.year - dob.year
  age -= 1 if dob.strftime("%m%d").to_i > today.strftime("%m%d").to_i
  age
end

dob = Date.new(1976, 4, 10)
age(dob)
#=> 35
dob = Date.new(1976, 5, 10)
age(dob)
#=> 34
fl00r
  • 82,987
  • 33
  • 217
  • 237
  • this function will be defined in the controller. However, after @persons = Person.find(:all), my @persons variable is already at the view, and I did not want to include this code at my view, thinking it will break the MVC concept ! – azinyue Apr 12 '11 at 14:38
  • You should add it into helper as a helper method – fl00r Apr 12 '11 at 14:43
3

Apologies in advance...I'm still learning Ruby:

require 'date'
dob = Date.new(1976, 7, 4)
now = Date.today
age = ((now - dob) / 365.25).to_i

I'm guessing there's a better way...?

  • Edit: 365 wasn't correct. But I'm not satisfied with 365.25. I'm going to upvote Vadim's for that reason. –  Apr 10 '11 at 19:15
1

Rails has a couple of Date-Helpers, among them distance_of_time_in_words: http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-distance_of_time_in_words.

As far as I remember it adds an "about x years", so it might be not useful in your particular situation unless you take a look at the source and adapt it.

Otherwise you can calculate with years directly calling Date.today.year (or dob.year).

Markus Proske
  • 3,356
  • 3
  • 24
  • 32
-2

This code seems to work for me with a few test ages

age = ((Date.today - dob).to_i / 365.25).ceil

where you define dob as the date object.