Skip to content

Instantly share code, notes, and snippets.

@banister
Created January 19, 2012 03:45
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 banister/1637648 to your computer and use it in GitHub Desktop.
Save banister/1637648 to your computer and use it in GitHub Desktop.
class Match
attr_accessor :matcher, :action
def initialize(matcher, action)
@matcher, @action = matcher, action
end
end
class SwitchBitch
def initialize(value, &block)
@value = value
@match_list = []
instance_exec &block
end
def case_(matcher, &block)
@match_list << Match.new(matcher, block)
end
def breakout
throw :breakout
end
def find_first_match_index
@match_list.find_index { |m| m.matcher == @value }
end
def run
if !(index = find_first_match_index)
puts "no matches!"
return
end
catch :breakout do
@match_list[index..-1].each do |match|
instance_exec(&match.action)
end
end
end
end
def switch(value, &block)
SwitchBitch.new(value, &block).run
nil
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment