Get person's age in Ruby

前端 未结 24 2965
忘了有多久
忘了有多久 2020-11-27 10:32

I\'d like to get a person\'s age from its birthday. now - birthday / 365 doesn\'t work, because some years have 366 days. I came up with the following code:

24条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 11:01

    I had to deal with this too, but for months. Became way too complicated. The simplest way I could think of was:

    def month_number(today = Date.today)
      n = 0
      while (dob >> n+1) <= today
        n += 1
      end
      n
    end
    

    You could do the same with 12 months:

    def age(today = Date.today)
      n = 0
      while (dob >> n+12) <= today
        n += 1
      end
      n
    end
    

    This will use Date class to increment the month, which will deal with 28 days and leap year etc.

提交回复
热议问题