Skip to content

Instantly share code, notes, and snippets.

@jspooner
Created March 31, 2011 15:56
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jspooner/896635 to your computer and use it in GitHub Desktop.
Save jspooner/896635 to your computer and use it in GitHub Desktop.
Extend the Ruby Time object with a method that will find the next weekday.
class Time
class << self
def next(day, from = nil)
day = [:sunday,:monday,:tuesday,:wednesday,:thursday,:friday,:saturday].find_index(day) if day.class == Symbol
one_day = 60 * 60 * 24
original_date = from || now
result = original_date
result += one_day until result > original_date && result.wday == day
result
end
end
end
puts Time.now
puts Time.next(4) # thursday
puts Time.next(:tuesday) # tuesday
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment