我正在编写一个用 ruby 编写的小实用程序,它广泛使用嵌套哈希。目前,我正在检查对嵌套哈希元素的访问,如下所示:
structure = { :a => { :b => 'foo' }}
# I want structure[:a][:b]
value = nil
if structure.has_key?(:a) && structure[:a].has_key?(:b) then
value = structure[:a][:b]
end
有一个更好的方法吗?我希望能够说:
value = structure[:a][:b]
And get nil
if :a 不是关键structure
, etc.
传统上,你确实必须做这样的事情:
structure[:a] && structure[:a][:b]
然而,Ruby 2.3添加了一个方法Hash#dig https://ruby-doc.org/core-2.3.0/Hash.html#method-i-dig这使得这种方式更加优雅:
structure.dig :a, :b # nil if it misses anywhere along the way
有一种宝石叫ruby_dig https://github.com/mottalrd/hash_dig_and_collect/这将为您进行反向修补。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)