简体   繁体   English

如果嵌套哈希中不存在密钥,则创建密钥

[英]Create key if it doesn't exist in nested hashes

I've been trying to figure out how to write this ruby code more eloquently. 我一直在尝试找出如何更雄辩地编写此ruby代码。 Does someone have a better solution? 有人有更好的解决方案吗?

a[:new] = {} if a[:new].nil?
a[:new].merge!( { new_key => new_value } )

is there a way to write this in a more elegant way? 有没有一种更优雅的方式来写这个? I come across this a lot when dealing with nested hashes that need to check whether an key exist and if not, create it. 在处理需要检查密钥是否存在以及是否创建密钥的嵌套哈希时,我遇到了很多问题。

Write it as below taking the help of Hash#to_h and NilClass#to_h Hash#to_hNilClass#to_h的帮助下,将其编写如下

a[:new] = a[:new].to_h.merge( { new_key => new_value } )

Example : 范例:

hsh1[:a] # => nil
hsh1[:a] = hsh1[:a].to_h.merge({1=>2})
hsh1[:a] # => {1=>2}

hsh2 = {:a => {'k' => 2}}
hsh2[:a] # => {"k"=>2}
hsh2[:a] = hsh2[:a].to_h.merge({1=>2})
hsh2 # => {:a=>{"k"=>2, 1=>2}}

Do this at the beginning: 在开始时执行此操作:

a = Hash.new{|h, k| h[k] = {}}

then, without caring whether a has a key :new or not, do 然后,不关心a是否具有密钥:new与否,执行

a[:new].merge!(new_key => new_value)

or 要么

a[:new][new_key] = new_value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM