简体   繁体   中英

change value in hash using an array of keys in ruby

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM