Ruby - set the value of a nested hash from an array of keys

I learned from Access to the nested hash element specified by the key array )

what if i have an array

array = ['person', 'age']

and I have a nested hash

hash = {:person => {:age => 30, :name => 'tom'}}

I can get the age value using

array.inject(hash, :fetch)

But how would I then set the value: age to 40 with an array of keys?

+4
source share
2 answers

You can get a hash containing the last key in the array (by deleting the last element), and then set the key 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 do not want to modify the array, you can use .lastand [0...-1]:

keys = array.map(&:to_sym)

key = keys.last
keys[0...-1].inject(hash, :fetch)[key] = 40
+7
source

:

def set_hash_value(h, array, value)
  curr_key = array.first.to_sym
  case array.size
  when 1 then h[curr_key] = value
  else set_hash_value(h[curr_key], array[1..-1], value)
  end
  h
end

set_hash_value(hash, array, 40)
  #=> {:person=>{:age=>40, :name=>"tom"}}
0

All Articles