How to change Hash values?

Adam Nonymous picture Adam Nonymous · May 1, 2009 · Viewed 118.5k times · Source

I'd like to replace each value in a hash with value.some_method.

For example, for given a simple hash:

{"a" => "b", "c" => "d"}` 

every value should be .upcased, so it looks like:

{"a" => "B", "c" => "D"}

I tried #collect and #map but always just get arrays back. Is there an elegant way to do this?

UPDATE

Damn, I forgot: The hash is in an instance variable which should not be changed. I need a new hash with the changed values, but would prefer not to define that variable explicitly and then loop over the hash filling it. Something like:

new_hash = hash.magic{ ... }

Answer

kch picture kch · May 1, 2009
my_hash.each { |k, v| my_hash[k] = v.upcase } 

or, if you'd prefer to do it non-destructively, and return a new hash instead of modifying my_hash:

a_new_hash = my_hash.inject({}) { |h, (k, v)| h[k] = v.upcase; h } 

This last version has the added benefit that you could transform the keys too.