从嵌套哈希中的键字符串中动态查找值

时间:2014-04-18 02:00:22

标签: ruby json hash

我有一个名为x_value的用户输入字符串,其值包含ticker|high之类的内容。只要有|,就表明后者是前者的孩子。该方法的目的是在散列中返回特定值。

sections = []
object.x_value.split('|').each do |part|
  sections << part.to_sym
end

然后我想深入挖掘数据哈希并检索最后一个键的值。

data = {"ticker":{"high":529.5,"low":465,"avg":497.25,"vol":7520812.018}}

在这个例子中

data[sections[0]][sections[1]]返回预期的529.5值。但是,用户可能具有不同的哈希值和嵌套键/值的深度。我怎么写这个?

我尝试了data[sections],但这没有用。

2 个答案:

答案 0 :(得分:3)

使用Enumerable#reduce

data = {"ticker" => {"high" => 529.5, "low" => 465,"avg" => 497.25,"vol" => 7520812.018}}
"ticker|high".split('|').reduce(data) { |dat,val| dat[val] } #=> 592.5

更多示例:

data = {"more_ticker" => {"ticker" => {"high" => 529.5, "low" => 465,"avg" => 497.25,"vol" => 7520812.018}}}
"more_ticker|ticker|avg".split('|').reduce(data) { |dat,val| dat[val] } 
#=> 497.25

答案 1 :(得分:1)

你也可以使用递归:

def getit(hash, x_value)
  recurse(hash, x_value.split('|'))
end

def recurse(hash, keys)
  k = keys.shift
  keys.empty? ? hash[k] : recurse(hash[k], keys)
end

data = {"ticker" => {"high" => 529.5, "low" => 465}}
getit(data, "ticker|high")            #=> 529.5
getit(data, "ticker")                 #=> {"high"=>529.5, "low"=>465}

data = {"more_ticker" => {"ticker" => {"high" => 529.5, "low" => 465}}}
getit(data, "more_ticker|ticker|low") #=> 465
getit(data, "more_ticker|ticker|avg") #=> nil