Created
June 17, 2013 09:22
-
-
Save ggPeti/5795723 to your computer and use it in GitHub Desktop.
Hash extension with key and value mapper methods.
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 map_keys | |
Hash[self.map { |key, value| [yield(key), value] }] | |
end | |
def map_keys! | |
keys.each { |key| self[yield(key)] = delete key } | |
self | |
end | |
def map_values | |
Hash[self.map { |key, value| [key, yield(value)] }] | |
end | |
def map_values! | |
each { |key, value| self[key] = yield(value) } | |
self | |
end | |
end |
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
describe Hash do | |
describe "#map_keys" do | |
it "should return with a new Hash whose keys are mapped with the given block" do | |
result = { key1: "value1" }.map_keys { |key| "#{key}_mapped".to_sym } | |
result.should == { key1_mapped: "value1" } | |
end | |
it "should not change the original hash" do | |
hash = { key1: "value1" } | |
hash.map_keys { |key| "#{key}_mapped".to_sym } | |
hash.should == { key1: "value1" } | |
end | |
end | |
describe "#map_keys!" do | |
it "should return with a Hash whose keys are mapped with the given block" do | |
result = { key1: "value1" }.map_keys! { |key| "#{key}_mapped".to_sym } | |
result.should == { key1_mapped: "value1" } | |
end | |
it "should change the Hash's keys with the given block" do | |
hash = { key1: "value1" } | |
hash.map_keys! { |key| "#{key}_mapped".to_sym } | |
hash.should == { key1_mapped: "value1" } | |
end | |
describe "#map_values" do | |
it "should return with a new Hash whose values are mapped with the given block" do | |
result = { key1: "value1" }.map_values { |value| "#{value}_mapped" } | |
result.should == { key1: "value1_mapped" } | |
end | |
it "should not change the original hash" do | |
hash = { key1: "value1" } | |
hash.map_values { |value| "#{value}_mapped" } | |
hash.should == { key1: "value1" } | |
end | |
end | |
describe "#map_values!" do | |
it "should return with a Hash whose values are mapped with the given block" do | |
result = { key1: "value1" }.map_values! { |value| "#{value}_mapped" } | |
result.should == { key1: "value1_mapped" } | |
end | |
it "should change the Hash's values with the given block" do | |
hash = { key1: "value1" } | |
hash.map_values! { |value| "#{value}_mapped" } | |
hash.should == { key1: "value1_mapped" } | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment