[Rails] calculate users age

Jonas Elfström jonelf at gmail.com
Tue Jan 24 08:55:31 GMT 2006


On 1/23/06, SB <richstyles at gmail.com> wrote:
> Weird, I was just writing something like this in the course of
> learning ruby.  I doubt you'll learn anything by just posting a random
> question and expecting an answer.  You should at least give it a stab.
>
> Hopefully, a more experienced ruby programmer will give me advice to
> improve my code.
>
> Here's my attempt:
> birthday.rb code
> require "time"

I would not recommend using the class time here since it does not
handle dates before 1970-01-01:
irb> Time.parse("1970-01-01 01:00")
=> Thu Jan 01 01:00:00 W. Europe Standard Time 1970
irb> Time.parse("1969-12-31")
ArgumentError: time out of range
irb> Time.parse("1970-01-01 00:59")
ArgumentError: time out of range

Try the Date in date.rb instead.
http://www.ruby-doc.org/core/files/lib/date_rb.html

Something like this looks like it works:
born=Date.strptime("1969-07-21")
age=Date.today.year-born.year
age=age-1 if Date.today.yday<born.yday

--
Jonas Elfström


More information about the Rails mailing list