1

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 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.