I am migrating my PHP code to Ruby and at some point I need to update hash elements inside of a loop. For example:
compositions.each_pair do |element,params|
params['composition'].each_pair do |item,data|
data['af'] /= params['af sum']
data['mf'] /= params['mass']
end
end
I could make it using item indexes, but it will be ugly. Is there a nice way to link the loop variables to the corresponding hash items? In PHP I would write &$params
and &$data
in the corresponding loops. Or may be a better suggestion?
Update
Two tests to demonstrate the problem. The first one:
a={'a'=>1, 'b'=>2, 'c'=>3}
a.each_pair do |k,v|
v += 1
end
p a # => {"a"=>1, "b"=>2, "c"=>3}
and the second
a.each_pair do |k,v|
a[k] += 1
end
p a # => {"a"=>2, "b"=>3, "c"=>4}
Update2
Thanks to Mladen (see below), I have understood the difference between these two cases. However, I still have a question: how to update data
item (not just its own items)? Let's say we add
data = data['af'] + data['mf']
to the inner loop.