Skip to content

Instantly share code, notes, and snippets.

@blambeau
Created November 22, 2011 09:00
Show Gist options
  • Save blambeau/1385245 to your computer and use it in GitHub Desktop.
Save blambeau/1385245 to your computer and use it in GitHub Desktop.
Fun destructuring in Ruby 1.9
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