LoginSignup
5
5

More than 5 years have passed since last update.

Rubyで第N曜日を求める(define_methodとsendを使う)

Posted at

各曜日の配列を返すメソッド(sundays .. saturdays)をdefine_method()で定義する。
また、days()に渡すブロック内において曜日を判断するメソッド(sunday? .. saturday?)をsend()で呼び出す。

require 'date'

class Date
  %w[sunday monday tuesday wednesday thursday friday saturday].each{ |day|
    define_method("#{day}s") { days { |date| date.send("#{day}?".to_sym) } }
  }
  def days
    firstday = self.firstday
    lastday = self.lastday
    results = []
    firstday.upto(lastday) {|date|
      results << date if yield date
    }
    results
  end
  def firstday
    Date.new(self.year, self.month, 1)
  end
  def lastday
    next_month = self >> 1
    next_month_first_day = next_month.firstday
    next_month_first_day - 1
  end
end
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5