Skip to content

Instantly share code, notes, and snippets.

@ggPeti
Created June 17, 2013 09:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ggPeti/5795723 to your computer and use it in GitHub Desktop.
Save ggPeti/5795723 to your computer and use it in GitHub Desktop.
Hash extension with key and value mapper methods.
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
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