7.23. Determining the Number of Days in a Month

At the time of this writing, there is no built-in function to do this. You can easily write a simple method for this:

require 'date'
def month_days(month,year=Date.today.year)
  mdays = [nil,31,28,31,30,31,30,31,31,30,31,30,31]
  mdays[2] = 29 if Date.leap?(year)
  mdays[month]
end

days = month_days(5)             # 31 (May)
days = month_days(2,2000)        # 29 (February 2000)
days = month_days(2,2100)        # 28 (February 2000)

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.