【问题标题】:Search for key-value from array of nested hash in ruby从 ruby​​ 中的嵌套哈希数组中搜索键值
【发布时间】:2014-12-23 10:49:05
【问题描述】:

我有嵌套哈希数组,即,

@a = [{"id"=>"5", "head_id"=>nil,
         "children"=>
             [{"id"=>"19", "head_id"=>"5",
                 "children"=>
                     [{"id"=>"21", "head_id"=>"19", "children"=>[]}]},
             {"id"=>"20", "head_id"=>"5",
                 "children"=>
                     [{"id"=>"22", "head_id"=>"20", "children"=>[]}, {"id"=>"23"}]
             }]
     }]

我需要键名为“id”的所有值的数组。像@b = [5,19,21,20,22,23] 我已经尝试过这个'@a.find { |h| h['id']}`。 有谁知道如何获得这个?

谢谢。

【问题讨论】:

  • 这也有效:@a.to_s.scan(/(?<=\"id\"=>\")\d+/).map(&:to_i) #=> [5, 19, 21, 20, 22, 23].
  • @CarySwoveland 太棒了它的工作就像魅力一样。谢谢

标签: ruby-on-rails ruby arrays hash


【解决方案1】:

您可以为Array 类对象创建新方法。

class Array
  def find_recursive_with arg, options = {}
    map do |e|
      first = e[arg]
      unless e[options[:nested]].blank?
        others = e[options[:nested]].find_recursive_with(arg, :nested => options[:nested])
      end
      [first] + (others || [])
    end.flatten.compact
  end
end

使用这个方法会像

@a.find_recursive_with "id", :nested => "children"

【讨论】:

  • 我似乎无法找到 map 在这里的工作原理。如果能给出解释就好了。
  • 加一为解决方案
  • mapeach 类似,区别在于each 返回您调用它的array,但map 在此示例中将e 元素替换为最后一行@ 987654332@ 将替换为数组中的每个元素。另见Ruby map
【解决方案2】:

可以这样做,使用recursion

def traverse_hash
  values = []
  @a = [{"id"=>"5", "head_id"=>nil,
     "children"=>
         [{"id"=>"19", "head_id"=>"5",
             "children"=>
                 [{"id"=>"21", "head_id"=>"19", "children"=>[]}]},
         {"id"=>"20", "head_id"=>"5",
             "children"=>
                 [{"id"=>"22", "head_id"=>"20", "children"=>[]}, {"id"=>"23"}]
         }]
 }] 
 get_values(@a)
end

def get_values(array)   
  array.each do |hash|        
    hash.each do |key, value|
      (value.is_a?(Array) ? get_values(value) : (values << value)) if key.eql? 'id'
    end
  end    
end

【讨论】:

    猜你喜欢
    • 2015-03-28
    • 2015-05-10
    • 2013-02-08
    • 2020-07-02
    • 2014-01-02
    • 1970-01-01
    • 2017-07-30
    • 1970-01-01
    • 2016-03-02
    相关资源
    最近更新 更多