[英]Ruby - Set Value of nested hash from array of keys
I learned from Access nested hash element specified by an array of keys )我从由一组键指定的 Access 嵌套散列元素中学到了)
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?但是我将如何使用键数组将 :age 的值设置为 40 呢?
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]
:如果您不想修改数组,可以使用
.last
和[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.您可以考虑使用Rodash gem 中的set方法,以便将深度嵌套的值设置为哈希。
require 'rodash'
hash = { person: { age: 30, name: 'tom' } }
key = [:person, :age]
value = 40
Rodash.set(hash, key, value)
hash
# => {:person=>{:age=>40, :name=>"tom"}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.