基本上我想使用 #dig.
我的必须是这样的:
hash = {
:first => {
:second => [1,2,3,4]
}
}
Run Code Online (Sandbox Code Playgroud)
我会用 Hash#dig
hash.dig(:first, :second) = [1,2,3,4]
Run Code Online (Sandbox Code Playgroud)
我怎样才能分配这个值?
您可以创建一个行为像您想要的哈希。Hash.new接受一个在键查找失败时调用的块。发生这种情况时,我们可以创建一个空哈希:
hash = Hash.new { |hash, key| hash[key] = Hash.new(&hash.default_proc) }
hash[:first][:second] = [1, 2, 3, 4]
hash # => {:first=>{:second=>[1, 2, 3, 4]}}
Run Code Online (Sandbox Code Playgroud)
请注意,仅访问不存在的密钥将导致创建新的哈希:
hash.dig(:a, :b, :c) # => {}
hash # => {:first=>{:second=>[1, 2, 3, 4]}, :a=>{:b=>{:c=>{}}}}
hash[:foo].nil? # => false
Run Code Online (Sandbox Code Playgroud)
dig 不能用于为哈希分配值,此方法仅用于访问值。
对于您的情况,您可以执行以下两件事之一:
hash = { first: { second: [1, 2, 3, 4] } }
Run Code Online (Sandbox Code Playgroud)
或者 :
hash[:first] = { second: [1, 2, 3, 4] }
Run Code Online (Sandbox Code Playgroud)
您还可以使用该文章中的方法:How to setdynamic value of Nested key in Ruby hash
他们创建了一种新的哈希方法来动态地将嵌套值分配给哈希。