Change (and update) values of hash


#1

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}


#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}

?


#3

On Thu, Mar 12, 2009 at 11:10 AM, Jason L.
removed_email_address@domain.invalid 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.


#4

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?


#5

On Thu, Mar 12, 2009 at 11:37 AM, lasitha removed_email_address@domain.invalid
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.


#6

On Thu, Mar 12, 2009 at 12:06 PM, Jason L.
removed_email_address@domain.invalid 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.


#7

On Thu, Mar 12, 2009 at 12:42 PM, lasitha removed_email_address@domain.invalid
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.


#8

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

On Thu, Mar 12, 2009 at 12:42 PM, lasitha
removed_email_address@domain.invalid 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
removed_email_address@domain.invalid