-5

Sorry Im new to rails. I just found a way to calculate the age in a model from here : Get person's age in Ruby

The function is this :

def age
  now = Time.now.utc
  now.year - birthday.year - (birthday.to_time.change(:year => now.year) > now ? 1 : 0)
end

Can some one please explain whats happening in the third line? I can't understand this :

(birthday.to_time.change(:year => now.year) > now ? 1 : 0)
Community
  • 1
  • 1
THpubs
  • 7,804
  • 16
  • 68
  • 143

1 Answers1

2

That sentence is only trying to check if the birthday has already passed for the current year. If it has, then

(birthday.to_time.change(:year => now.year) > now ? 1 : 0)

will equal to 0. otherwise 1. this will be then subtracted like this:

now.year - birthday.year - 1 or now.year - birthday.year - 0

Hope that clarifies your doubt.

Just a suggestion, I would rather use irb and break up above code in smaller pieces and see what each part does exactly for myself. This would help me understand stuff better.

dewdrops
  • 277
  • 2
  • 8