ric*_*ick 4 ruby arrays hash ruby-on-rails
我有嵌套哈希数组,
@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"}]
}]
}]
Run Code Online (Sandbox Code Playgroud)
我需要所有具有键名称'id'的值的数组.比如@b = [5,19,21,20,22,23]我已经试过这个'@a.find {| h | H [ 'ID']}`.有谁知道如何得到这个?
谢谢.
您可以为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
Run Code Online (Sandbox Code Playgroud)
使用这种方法就像
@a.find_recursive_with "id", :nested => "children"
Run Code Online (Sandbox Code Playgroud)