简体   繁体   中英

Ruby - Set Value of nested hash from array of keys

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

You could use recursion:

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"}}

You can consider using the set method from the rodash gem in order to set a deeply nested value into a hash.

require 'rodash'

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

key = [:person, :age]
value = 40

Rodash.set(hash, key, value)

hash
# => {:person=>{:age=>40, :name=>"tom"}}

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