Ruby 嵌套哈希中任意位置的键的任何实例

Ruby 嵌套哈希中任意位置的键的任何实例,ruby,Ruby,给定这样的散列: h = { "actual_amount" => 20, "otherkey" => "value", "otherkey2" => [{"actual_amount" => 30, "random_amount" => 45}] } 如果存在任意数量的嵌套层,是否有一种简单的方法来提取键的所有键值对(或仅值),这些键值对是actual\u amount?我假设键的值是文本或哈希数组 这个问题显然需要递归解决方案 def amount

给定这样的散列:

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

如果存在任意数量的嵌套层,是否有一种简单的方法来提取键的所有键值对(或仅值),这些键值对是
actual\u amount

我假设键的值是文本或哈希数组

这个问题显然需要递归解决方案

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
然后


使用Cary提供的哈希作为输入:

▶ 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]

您的“哈希”无效。如果val有
实际金额
,是否要获取密钥?如果是这样的话,试试这个
h.map{| k,v | pk If(v.is_a?(数组)和&v.first[“actual_amount”].present?}
似乎需要使用递归?
amounts(h)
  #=> [20, 30, 40] 
▶ 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]