从ruby中的嵌套哈希数组中搜索键值

时间:2014-12-23 10:49:06

标签: ruby-on-rails ruby arrays hash

我有嵌套哈希数组,

@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']}`。 有谁知道如何得到这个?

感谢。

2 个答案:

答案 0 :(得分:5)

您可以为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"

答案 1 :(得分:4)

可以使用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