簡體   English   中英

Ruby - 從鍵數組中設置嵌套散列的值

[英]Ruby - Set Value of nested hash from array of keys

我從由一組鍵指定的 Access 嵌套散列元素中學到

如果我有一個數組

array = ['person', 'age']

我有一個嵌套的哈希

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

我可以通過使用獲得年齡的價值

array.inject(hash, :fetch)

但是我將如何使用鍵數組將 :age 的值設置為 40 呢?

您可以獲得包含數組中最后一個鍵的哈希(通過刪除最后一個元素),然后設置鍵的值:

array.map!(&:to_sym) # make sure keys are symbols

key = array.pop
array.inject(hash, :fetch)[key] = 40

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

如果您不想修改數組,可以使用.last[0...-1]

keys = array.map(&:to_sym)

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

您可以使用遞歸:

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

您可以考慮使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM