Reputation: 1705
I have array of nested hash that is,
@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"}]
}]
}]
I need array of all values which have key name 'id'. like @b = [5,19,21,20,22,23] I have already try this '@a.find { |h| h['id']}`. Is anyone know how to get this?
Thanks.
Upvotes: 4
Views: 2556
Reputation: 17834
It can be done like this, using 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
Upvotes: 4
Reputation: 6100
You can create new method for Array
class objects.
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
Using this method will be like
@a.find_recursive_with "id", :nested => "children"
Upvotes: 5