月末の日を返す

その月の最大日付を返すユーティリティ - プログラムメモを見て僕も書いてみた。
僕ならこうかなぁ。

require 'date'

class Date
  def max_day
    max_days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    max_days[2] = 29 if self.leap?
    max_days[self.month]
  end
end

1.upto(12){|month|
  date = Date.new(2007, month, 1)
  puts "%2d: #{date.max_day}" % month
}


実行結果

 1: 31
 2: 28
 3: 31
 4: 30
 5: 31
 6: 30
 7: 31
 8: 31
 9: 30
10: 31
11: 30
12: 31

気にかけた点

  • Dateクラスに新しいメソッドを追加

Date#day があるので、それに合わせる形で、Date#max_day を追加した。
新しくクラスを作るよりもその方がスマートな気がしたので。

  • 月ごとの月末日を持つ配列を用意

値を参照するときに、月末日の配列[月] ってできると
直感的に分かりやすかなと思ったので。


と、ここまで書いてから思い出した。
Date を new するときに、
日のところに -1 を与えると月末を指定したことになるんだった。
ってことでこれでOKのようですね(´▽` )

require 'date'

1.upto(12){|month|
  date = Date.new(2007, month, -1)
  puts "%2d: #{date.day}" % month
}