Dlaw Dlaw - 1 year ago 72
Ruby Question

Ruby arrays and hash multi-dimensional issues

I have created an array of hashes that I want to access. I have actually been able to access the first two items but going through the third is where I couldn't...the code is below. I have tried to get it from related topics but they are as different as a Salmon is different from Fish.

arry =[{"A"=>{"name"=>"B","id"=>1,"sub"=>[{"name"=>"C","id"=>1},{"name"=>"D","id"=>2}]}}]

I have been able to pass through A to B by using this code:

print arry[0]['A']['name']

and I got "B"

now how do I get something like

"A B C" OR "A B D"?

Answer Source

The following returns ["A", "B", "C", "D"]:

#for trying out in `irb` this is fine, but I would recommend refactoring to smaller methods
[].tap do |result|
  result << arry[0].keys
  second_level_hash_names = arry.map {|hash| hash.values.map {|values_hash| values_hash["name"]}}.flatten
  third_level_hash_names = arry.map {|hash| hash.values.map {|values_hash| values_hash["sub"].map {|sub_hash| sub_hash["name"]}}}.flatten
  result << second_level_hash_names << third_level_hash_names

In your question you ask for ""A B C" OR "A B D"?" but I'm not sure which you're looking for and whether "C" or "D" is arbitrary. You can play with this code in irb and modify for your use case.