When business logic dictates that something only happens on Saturday, this snippet can help keep your code and tests legible.

module DatePredicates
  Date::DAYNAMES.each_with_index do |day_name, i|
    define_method "#{day_name}?" do i == wday end
  end
end
 
class Date
  include DatePredicates
end

Date.today.Tuesday?
=> true

One Comment

  1. Jeremy Voorhis

    I’d prefer to have the methods begin with a lower-case letter. This is grammatically correct, but I’ll probably misspell these the first couple of times.

Leave a Comment

Enclose code in <code lang="ruby"></code> if you care.
Preview your comment using the button below.