Misha Moroshko Misha Moroshko - 2 months ago 6
Ruby Question

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

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 ?

Answer

This applies the function f to each value in hash:

hash.update(hash){|key,v1| f(v1)}