Created
August 4, 2009 08:30
-
-
Save mudge/161108 to your computer and use it in GitHub Desktop.
Map over a Ruby hash, replacing the values for each key.
This file contains hidden or 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
# Map over a hash, replacing the values for each key. | |
x = {:a => 1, :b => 2} | |
#=> {:a => 1, :b => 2} | |
x.merge(x) { |k, v| v * 2 } | |
#=> {:a => 2, :b => 4} | |
# If you want to replace Enumerable's map... | |
class Hash | |
def map(&block) | |
merge(self, &block) | |
end | |
end | |
# then... | |
x.map { |k, v| v * 2 } | |
#=> {:a => 2, :b => 4} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment