Skip to content

Instantly share code, notes, and snippets.

@captainpete
Created May 26, 2011 06:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save captainpete/992631 to your computer and use it in GitHub Desktop.
Save captainpete/992631 to your computer and use it in GitHub Desktop.
The Wesley Date Challenge
# Uses 1.9.2
# Makes use of existing day names in Date class
# Demeter is happy
# Support full and abbreviated names
# Doesn't use seconds (avoids error scenarios when crossing DST & leap-seconds)
class DDate < Date
def self.next(target_dayname)
target_wday = ABBR_DAYNAMES.index { |dayname| target_dayname =~ Regexp.new(dayname) }
diff = target_wday - today.wday
diff += 7 if diff < 0
today + diff
end
end
# See how she runs
{ "Monday" => Date.civil(2011, 05, 30),
"Tuesday" => Date.civil(2011, 05, 31),
"Wednesday" => Date.civil(2011, 06, 01),
"Thursday" => Date.civil(2011, 05, 26),
"Friday" => Date.civil(2011, 05, 27),
"Saturday" => Date.civil(2011, 05, 28),
"Sunday" => Date.civil(2011, 05, 29)
}.each do |name, date|
result = DDate.next name
message = result == date ? "OK" : "Expected #{date}"
puts "#{name}: #{result} #{message}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment