Skip to content

Instantly share code, notes, and snippets.

@philosodad
Created March 22, 2012 22:59
Show Gist options
  • Save philosodad/2165289 to your computer and use it in GitHub Desktop.
Save philosodad/2165289 to your computer and use it in GitHub Desktop.
monkey patch of the enumerable class that adds a "to_hash" method
module Enumerable
def hashmogrify(&block)
hash = {}
self.each do |e|
result = block.call(e)
if result.is_a?(Array)
hash[result[0]] = result[1]
else
hash[result] = e
end
end
hash
end
end
describe "Enumerable#to_hash" do
it "creates a hash from any enumerable object" do
[].hashmogrify(&:whatever).should be_a Hash
end
it "uses an object attribute to create the keys for the hash" do
["foo", "barr", "bazzz"].to_hash(&:length).keys.should == [3,4,5]
end
it "can accept a block to define a custom key function" do
hash = ["foo", "bar", "baz"].hashmogrify { |s| s.reverse }
hash.keys.should == ["oof", "rab", "zab"]
end
it "sets the values in the hash to the enumerated objects" do
hash = ["foo", "bar", "baz"].hashmogrify { |s| s.reverse }
hash.values.should == ["foo", "bar", "baz"]
end
it "can accept a block to define both the keys and the values in the hash" do
hash = ["foo", "barr", "bazzz"].hashmogrify { |s| [s, s.length] }
hash.should == {
"foo" => 3,
"barr" => 4,
"bazzz" => 5
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment