Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Hash value traversal and changing value is not working

a = {"a" => 100, "b" => 200, "c" => 300}

b = a.map{|k,v| v = v + 10}

is returning an array, i need to change the values of a hash by call by reference

I am expecting the following output

{"a" => 110, "b" => 210, "c" => 310}

Thanks

like image 547
Sreeraj Avatar asked Nov 28 '22 10:11

Sreeraj


2 Answers

Maybe you can do something like this:

a.keys.each do |key| a[key] += 10 end
like image 32
Bjoernsen Avatar answered Nov 30 '22 23:11

Bjoernsen


Here's my non-mutating one-liner :P

Hash[original_hash.map { |k,v| [k, v+10] }]

Gotta love ruby one-liners :)

like image 103
d11wtq Avatar answered Nov 30 '22 22:11

d11wtq