change value in hash using an array of keys in ruby

487 Views Asked by At

i was wondering if it is possible to access an value of a hash with an array of keys as described in the post ruby use array tvalues to index nested hash of hash. My aim is not just to access this value but to change this value. As I understood

keys.inject(hash, :fetch)

returns the value of the hash-value determined by the key-array and not it's reference. How can I accomplish to modify this value?

I know it's bad style to modify an object instead of making a copy and working with immutables but in severel cases it seems much more comfortable to do it the short way.

Thanks a lot.

1

There are 1 best solutions below

0
On BEST ANSWER

Use all but the last key to get the most deeply nested Hash, then assign normally using the last key.

keys[0...-1].inject(hash, :fetch)[keys.last] = value

Ruby doesn't have references so you can't reassign the value directly. Instead you have to reassign the object pointer, which means going up one level of nesting.