Created
November 22, 2011 09:00
-
-
Save blambeau/1385245 to your computer and use it in GitHub Desktop.
Fun destructuring in Ruby 1.9
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Hash | |
def with(&block) | |
block.call *block.parameters.map{|x| self[x.last]} | |
end | |
end | |
# Example | |
h = {:name => "blambeau", :hobby => "ruby"} | |
h.with{|hobby| puts hobby} | |
# Spec | |
require 'rspec/autorun' | |
describe "Hash#with" do | |
it "should yield a 1-param block with the correct value" do | |
{:name => "blambeau"}.with{|name| | |
name.should eq("blambeau") | |
} | |
end | |
it "should yield a 2-param block with the correct values" do | |
{:name => "blambeau", :hobby => "ruby"}.with{|hobby,name| | |
hobby.should eq("ruby") | |
name.should eq("blambeau") | |
} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment