Skip to content

Instantly share code, notes, and snippets.

@ltcdnunez
Created August 19, 2012 01:55
Show Gist options
  • Save ltcdnunez/3390935 to your computer and use it in GitHub Desktop.
Save ltcdnunez/3390935 to your computer and use it in GitHub Desktop.
Default Hash Argument As Proc
example = Hash.new(Proc.new { raise Exception.new "Named action doesn't exist" }
example[:do_something_cool] = Proc.new { puts "I just did something cool!" }
example[:do_something_else_cool] = Proc.new { puts "I did another cool thing!" }
example[:do_something_cool].call
# => "I just did something cool!"
example[:do_something_else_cool].call
# => "I did another cool thing!"
example[:do_one_last_cool_thing].call
# => Exception: Named action doesn't exist
example = Hash.new do |hash, key|
Proc.new do |name|
raise Exepction.new "#{name} can't #{key.to_s.gsub("_", " ")}"
end
end
example[:did_something_cool] = Proc.new { |name| puts "#{name} just did something cool!" }
example[:did_something_else_cool] = Proc.new { |name| puts "#{name} did another cool thing!" }
example[:do_something_cool].call("John")
# => "John just did something cool!"
example[:do_something_else_cool].call("John")
# => "John did another cool thing!"
example[:do_one_last_cool_thing].call("Marvin")
# => Exception: Marvin can't do one last cool thing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment