bill bill - 3 months ago 20
Ruby Question

Using .update to update values

If we have a hash and we want to update one of the values or keys we can easily use the .

update
method like the following

def foo(params)
params+=1
end

hsh = {:a=>1,:b=>2,:c=>3}

hsh.update(hsh) do |key,oldVal|
foo(oldVal)
end

p hsh


However suppose a new
hash
, and I want to copy its properties into another
hash
and add one to the value. How would I exactly do this? Here is my attempt

def foo(params)
params+=1
end
new_hsh = {:a=>1,:b=>2,:c=>3}
hsh = {}
hsh.update(new_hsh) do |key,value,newVal|
newVal = foo(value)
end

p hsh


Which outputs
{:a=>1,:b=>2,:c=>3}
. So it is copying
new_hsh
, but not updating the
value
.

According to docs


Adds the contents of other_hash to hsh. If no block is specified, entries with duplicate keys are overwritten with the values from other_hash, otherwise the value of each duplicate key is determined by calling the block with the key, its value in hsh and its value in other_hash.


So it is copying like the docs say.. but how can I update it?

Thanks

EDIT

tried

def foo(params)
params+=1
end
new_hsh = {:a=>1,:b=>2,:c=>3}
hsh = {}
hsh.update(new_hsh) do |key,value,newVal|
foo(newVal)
end

p hsh

Answer

Here is another answer. This works but also modifies the new_hsh because of pattern matching? But you need to set the hsh = new_hsh before calling update on hsh.

def foo(params)
params+=1
end

new_hsh = {:a=>1,:b=>2,:c=>3}
hsh = new_hsh
hsh.update(hsh) do |key,value|
    hsh[key] = foo(value)
end

p hsh
Comments