Ruby通过变量访问哈希值

问题描述 投票:0回答:2

让我们将此视为我们的哈希c = {:test => {:foo => true}}

通常,如果我们想打印foo的值,我们会像这个c[:test][:foo]一样访问哈希,但我想基于我的变量动态访问它。

因此,让我们考虑以下变量path = [[:test],[:foo]]

我现在如何获取值true?我试过c[path],但它只是说nil。我错过了什么?

ruby-on-rails ruby
2个回答
2
投票

旧的好的递归Ruby 1.9+解决方案:

hash = {:test => {:foo => true}}
path = [[:test],[:foo]]

path.flatten.reduce(hash) { |h, p| h[p] }
#⇒ true

或者,正如@Stefan在评论中所建议的那样:

path.reduce(hash) { |h, (p)| h[p] }
# or even
path.reduce(hash) { |h, p| h[p.first] }

更具防御性:

path.flatten.reduce(hash) { |h, p| h.nil? ? nil : h[p] }

3
投票

你可以使用dig。你可以在这里查看挖掘文件Hash#dig

c = { :test => { :foo => true } }
c[:test][:foo]
#=> true

c.dig(:test, :foo)
#=> true

path = [:test, :foo]
c.dig(*path)
#=> true

您只需要传递层次结构

注意:在qazxsw poi中的qazxsw poi之前的qazxsw poi被称为splat运算符

© www.soinside.com 2019 - 2024. All rights reserved.