I'm trying to figure out nested arrays, particularly of the multi dimensional type. I've gone through two articles on them and are getting tripped up when the iteration is checking for strings.
# Array -
more_nested_array = [["hello", ["world", "new york"]], ["love", "ruby"]]
# Iteration-
more_nested_array.each do |element|
element.each do |inner_element|
if inner_element.is_a?(Array)
inner_element.each do |third_layer_element|
end
end
end
end
So it is using the if statement because supposedly in some iteration there are strings. This reference to strings is confusing me since it looks like it's just a bunch of arrays. Can someone explain please?
The check is needed because the loops are hard-coded for this given tree (or nested arrays, if you prefer).
Removing the check :
more_nested_array = [["hello", ["world", "new york"]], ["love", "ruby"]]
# Iteration-
more_nested_array.each do |element|
element.each do |inner_element|
inner_element.each do |third_layer_element|
puts third_layer_element
end
end
end
outputs:
undefined method `each' for "hello":String (NoMethodError)
because not every inner_element is an array or responds to each.
With this kind of structure, it would be preferrable to write a recursive method in order to parse the tree, instead of hard-coding the tree depth and node classes.
more_nested_array = [["hello", ["world", "new york"]], ["love", "ruby"]]
def parse_tree(node, current_depth = 0)
if node.respond_to?(:each)
node.each do |child|
parse_tree(child, current_depth + 1)
end
else
puts "Found #{node.inspect} at depth #{current_depth}"
end
end
parse_tree(more_nested_array)
It outputs:
Found "hello" at depth 2
Found "world" at depth 3
Found "new york" at depth 3
Found "love" at depth 2
Found "ruby" at depth 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With