Created
May 26, 2011 06:06
-
-
Save captainpete/992631 to your computer and use it in GitHub Desktop.
The Wesley Date Challenge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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