Skip to content

Instantly share code, notes, and snippets.

@havenwood
Last active December 13, 2015 19:39
Show Gist options
  • Save havenwood/4964517 to your computer and use it in GitHub Desktop.
Save havenwood/4964517 to your computer and use it in GitHub Desktop.
Hash#map_value, Hash#map_key, Hash#map_pair.
class Hash
def map_value
each_pair.with_object({}) do |(key, value), result|
result[key] = yield value
end
end
def map_key
each_pair.with_object({}) do |(key, value), result|
result[yield key] = value
end
end
def map_pair &block
Hash[map &block]
end
end
hash = { aim: true }
#=> {:aim=>true}
hash.map_value &:to_s
#=> {:aim=>"true"}
hash.map_key &:to_s
#=> {"aim"=>true}
hash.map_pair { |k, v| [k.to_s, v.to_s] }
#=> {"aim"=>"true"}
# Thanks to heftig for the refactor!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment