我有嵌套哈希数组,即
@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']}`。 有谁知道如何得到这个?
谢谢。
最佳答案
您可以为 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"
关于ruby-on-rails - 从 ruby 中的嵌套哈希数组中搜索键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27618828/