Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - Set Value of nested hash from array of keys

Tags:

arrays

ruby

hash

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?

like image 955
seanrclayton Avatar asked Jan 28 '15 23:01

seanrclayton


1 Answers

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
like image 136
August Avatar answered Oct 11 '22 07:10

August