2016-03-25 118 views
1

给定一个散列像这样的任何位置键的任何实例:在嵌套散列

h = { 
    "actual_amount" => 20, 
    "otherkey" => "value", 
    "otherkey2" => [{"actual_amount" => 30, "random_amount" => 45}] 
} 

其中存在任何数量的嵌套的层,有一个简单的方式来拔除所有的键 - 值对(或只是值actual_amount

+0

你的 “哈希” 是无效的。 – sawa

+0

如果** val **具有'actual_amount',您是否想获得**键**?如果是这样,试试这个'h.map {| k,v | (v.is_a?(Array)&& v.first [“actual_amount”]。present?)}' – Abhi

+0

似乎需要使用递归吗? – coderz

回答

1

我假定键的值是文字或散列数组。

这个问题清楚地要求递归解决方案。

def amounts(h) 
    h.each_with_object([]) do |(k,v),a| 
    case v 
    when Array 
     v.each { |g| a.concat amounts(g) } 
    else 
     a << v if k == "actual_amount" 
    end 
    end 
end 

假设

h = { 
    "actual_amount"=>20, 
    1=>2, 
    2=>[ 
     { "actual_amount"=>30, 
     3=>[ 
      { "actual_amount" => 40 }, 
      { 4=>5 } 
      ] 
     }, 
     { 5=>6 } 
    ] 
} 

然后

amounts(h) 
    #=> [20, 30, 40] 
2

使用散列,由卡里提供,作为输入:

▶ flatten = ->(inp) do 
▷ [*(inp.respond_to?(:map) ? inp.map(&:flatten) : inp)] 
▷ end 
▶ res = flatten(h).first 
▶ res.select.with_index do |_, i| 
▷ i > 0 && res[i - 1] == 'actual_amount' 
▷ end 
#⇒ [20, 30, 40]