Skip to content

Instantly share code, notes, and snippets.

@mudge
Created August 4, 2009 08:30
Show Gist options
  • Save mudge/161108 to your computer and use it in GitHub Desktop.
Save mudge/161108 to your computer and use it in GitHub Desktop.
Map over a Ruby hash, replacing the values for each key.
# 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