Thanks for pointing this out! I can’t imagine why I did not think of
this.
I am not in any way an endorser of trying to make code as short as
possible but out of curiosity I fixed my one-line class so that it now
correct but “unreadable”:
Here is a little bit i just put together.
I’ve not made it pretty and have only done some basic testing.
Context: this function is in a model which has a Date field called dob
it returns the age in “y years m months d days old” format skipping
values that are empty and pluralizing year month and day as appropriate.
ex: (Time.now = 2006/01/28)
dob [time_ago_in_words] [object.age_in_words]
2004-02-21 (age = 707 days) (1 year 11 months 7 days old)
2002-01-28 (age = 1461 days) (4 years old)
2005-08-20 (age = 161 days) (5 months 8 days old)
===========================
def age_in_words
if dob == nil
“–”
else
now = Time.now
ydiff = now.year - dob.year
mdiff = now.month - dob.month
ddiff = now.day - dob.day
if ((mdiff < 0) && (ydiff > 0))
y = ydiff - 1
m = mdiff + 12
else
y = ydiff
m = mdiff
end
if ((ddiff < 0) && (mdiff != 0))
m = m - 1
dim = Time.days_in_month(dob.month+m,dob.year+y)
d = (dim - dob.day) + now.day
else
d = ddiff
end
end
ys = "year"
ms = "month"
ds = "day"
if (y.abs > 1)
ys= ys.pluralize
end
if (m.abs > 1)
ms = ms.pluralize
end
if (d.abs > 1)
ds = ds.pluralize
end
year_string = (y != 0)?"#{y} #{ys} ":""
month_string = (m != 0)?"#{m} #{ms} ":""
day_string = (d != 0)?"#{d} #{ds}":""
return "#{year_string}#{month_string}#{day_string} old"
end