Skip to content

Instantly share code, notes, and snippets.

@duckinator
Forked from jbr/switch.rb
Last active June 13, 2016 10:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duckinator/8470407 to your computer and use it in GitHub Desktop.
Save duckinator/8470407 to your computer and use it in GitHub Desktop.
# In response to:
# http://mlomnicki.com/ruby/tricks-and-quirks/2011/02/10/ruby-tricks2.html
# Ruby 1.9.2 has some neat stuff that lets us make a readable
# alternative case statement that calls each method in turn.
# 1.9.2 features used:
# * hashes are ordered in 1.9.2
# * cool JSON-style hash syntax
# * concise lambda syntax
module Kernel
def switch(thing, hash)
hash.each do |method, proc|
return proc[] if method == :else || thing.send(method)
end
end
end
switch offer,
available: -> { order.submit },
cancelled: -> { order.reject },
postponed: -> { order.postpone },
else: -> { raise UnknownStateError.new }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment