Change (and update) values of hash

how would I do stuff to each value of a hash and return a modified hash?
h = {“a”=> 3, “b”=> 5}
multiply each value by 2 and return
h = {“a”=> 6, “b”=> 10}

this does what I need but does not modify the hash

h.each {|k,v| h[k]*2}

Is this the best solution:

h = {“a”=> 3, “b”=> 5}

x = {}

h.each {|k,v| x[k] = v*2}

=> {“a”=>3, “b”=>5}

h.replace(x)

=> {“a”=>6, “b”=>10}

?

On Thu, Mar 12, 2009 at 11:10 AM, Jason L.
[email protected] wrote:

how would I do stuff to each value of a hash and return a modified hash?
h = {“a”=> 3, “b”=> 5}
multiply each value by 2 and return
h = {“a”=> 6, “b”=> 10}

One way (among several):
$: irb
01> h = { ‘a’ => 3, ‘b’ => 5 }
→ {“a”=>3, “b”=>5}
02> h.inject(h) {|h, (k, v)| h[k] = v * 2; h }
→ {“a”=>6, “b”=>10}

solidarity,
lasitha.

This is much easier:
h.each {|k, v| h[k] = v * 2 }

thank you.

I was told it could be bad to change values during iteration. That is
why I proposed doing replace. what do you think?

On Thu, Mar 12, 2009 at 11:37 AM, lasitha [email protected]
wrote:

→ {“a”=>3, “b”=>5}
02> h.inject(h) {|h, (k, v)| h[k] = v * 2; h }
→ {“a”=>6, “b”=>10}

I’m being silly (its fun being silly with inject :).
This is much easier:
h.each {|k, v| h[k] = v * 2 }

lasitha.

On Thu, Mar 12, 2009 at 12:06 PM, Jason L.
[email protected] wrote:

This is much easier:
h.each {|k, v| h[k] = v * 2 }

thank you.

I was told it could be bad to change values during iteration. That is
why I proposed doing replace. what do you think?

There was a recent thread about this:
http://www.nabble.com/Iterating-a-changing-Hash-under-1.9.1-td22023417.html

I believe assigning values to existing keys is safe.

If in doubt, iterate over the keys instead:
h.keys.each {|k| h[k] = h[v] * 2 }

solidarity,
lasitha.

On Thu, Mar 12, 2009 at 12:42 PM, lasitha [email protected]
wrote:

If in doubt, iterate over the keys instead:
h.keys.each {|k| h[k] = h[v] * 2 }
~~~~
oops. should be h[k] = h[k] * 2
lasitha.

On Mar 12, 2009, at 3:12 AM, lasitha wrote:

On Thu, Mar 12, 2009 at 12:42 PM, lasitha
[email protected] wrote:

If in doubt, iterate over the keys instead:
h.keys.each {|k| h[k] = h[v] * 2 }
~~~~
oops. should be h[k] = h[k] * 2
lasitha.

Or use a little sugar:

h.keys.each {|k| h[k] *= 2 }

Rob B. http://agileconsultingllc.com
[email protected]