Skip to content

Instantly share code, notes, and snippets.

@smithrobs
Forked from practicingruby/refactoring patterns
Created October 2, 2010 19:33
Show Gist options
  • Save smithrobs/607915 to your computer and use it in GitHub Desktop.
Save smithrobs/607915 to your computer and use it in GitHub Desktop.
#substitute algorithm
# old:
#-----------------
require 'Date'
days = Date::ABBR_DAYNAMES
days.each do |day|
if (day == "Sun" || day == "Mon")
p "#{day} - Party time!"
elsif (day == "Mon")
p "#{day} - Need more coffee."
elsif (day == "Wed")
p "#{day} - Halfway there..."
elsif (day == "Fri")
p "#{day} - Whoooooohooooo!"
else
p "#{day} - Just another day."
end
end
# new:
#-----------------
require 'Date'
separator = " - "
date_output = lambda {|day| "#{day}#{separator}"}
msg = lambda do |msg,day|
p date_output.call(day) + msg
end
curried_msg = msg.curry
weekend_msg = curried_msg["Party time!"]
head_msg = curried_msg["Need more coffee."]
hump_msg = curried_msg["Halfway there."]
tail_msg = curried_msg["Almost..."]
boring_msg = curried_msg["Just another day."]
fns = {"Sun" => weekend_msg,
"Mon" => head_msg,
"Tue" => boring_msg,
"Wed" => hump_msg,
"Thu" => boring_msg,
"Fri" => tail_msg,
"Sat" => weekend_msg}
days = Date::ABBR_DAYNAMES
days.each do |day|
fns[day].call(day)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment