change (and update) values of hash

J

Jason Lillywhite

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

Jason Lillywhite

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}


?
 
L

lasitha

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.
 
L

lasitha

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}

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

lasitha.
 
J

Jason Lillywhite

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?
 
L

lasitha

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top