Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: What is the easiest method to update Hash values?

Tags:

ruby

hash

Say:

h = { 1 => 10, 2 => 20, 5 => 70, 8 => 90, 4 => 34 } 

I would like to change each value v to foo(v), such that h will be:

h = { 1 => foo(10), 2 => foo(20), 5 => foo(70), 8 => foo(90), 4 => foo(34) } 

What is the most elegant way to achieve this ?

like image 271
Misha Moroshko Avatar asked Mar 07 '11 04:03

Misha Moroshko


People also ask

How does Ruby calculate hash value?

To find a hash key by it's value, i.e. reverse lookup, one can use Hash#key . It's available in Ruby 1.9+.

How do you update Hashes?

Click Tools > Distribution > Distribution packages. From the shortcut menu for the package whose hash you want to update, click Reset package hash. This can take a few minutes on large packages.

How do you add to a hash?

Hash literals use the curly braces instead of square brackets and the key value pairs are joined by =>. For example, a hash with a single key/value pair of Bob/84 would look like this: { "Bob" => 84 }. Additional key/value pairs can be added to the hash literal by separating them with commas.


1 Answers

You can use update (alias of merge!) to update each value using a block:

hash.update(hash) { |key, value| value * 2 } 

Note that we're effectively merging hash with itself. This is needed because Ruby will call the block to resolve the merge for any keys that collide, setting the value with the return value of the block.

like image 137
Gareve Avatar answered Sep 22 '22 23:09

Gareve