I learned from Access nested hash element specified by an array of keys)
that if i have a array
array = ['person', 'age']
and I have a nested hash
hash = {:person => {:age => 30, :name => 'tom'}}
I can get the value of of age by using
array.inject(hash, :fetch)
But How would I then set the value of :age to 40 with the array of keys?
You can get the hash that contains the last key in the array (by removing the last element), then set the key's value:
array.map!(&:to_sym) # make sure keys are symbols
key = array.pop
array.inject(hash, :fetch)[key] = 40
hash # => {:person=>{:age=>40, :name=>"tom"}}
If you don't want to modify the array you can use .last
and [0...-1]
:
keys = array.map(&:to_sym)
key = keys.last
keys[0...-1].inject(hash, :fetch)[key] = 40
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With