Skip to content

Instantly share code, notes, and snippets.

@bradgessler
Created December 14, 2009 07:51
Show Gist options
  • Save bradgessler/255890 to your computer and use it in GitHub Desktop.
Save bradgessler/255890 to your computer and use it in GitHub Desktop.
class Switch
def initialize(obj, &block)
@obj, @procs = obj, []
instance_eval(&block)
@proc = @procs.detect{|p| p.call }
end
def call
@proc.call if @proc
end
def on(val, &block)
deffer(block) { val === @obj }
end
def responds_to(val,&block)
deffer(block) { @obj.respond_to?(val) }
end
private
def deffer(block, &condition)
@procs << lambda { return block.call if condition.call }
end
end
def switch(obj,&block)
Switch.new(obj,&block).call
end
out = switch "Dog farts" do
responds_to :<< do
"hey!"
end
responds_to :<< do
"I respond <<!"
end
on String do
"I'm a string!"
end
end
puts out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment