Nested arrays and strings in Ruby

I am trying to compute nested arrays, especially multidimensional type. I have looked at two articles about them and it worked when the iteration checks the rows.

# 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 uses an if statement because presumably there are lines in some iteration. This strings reference is confusing me as it looks like a bunch of arrays. Can someone explain please?

+3


source to share


2 answers


NoMethodError otherwise

Validation is necessary because the loops are hardcoded for the given tree (or nested arrays if you prefer).

Removing 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 everyone inner_element

is an array or responds to each

.

Recursive version

With this structure, it would be desirable to write a recursive method to parse the tree instead of hardcoding 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

      

+4


source


"hello"

is a string that is stored along with arrays like ["world", "new york"]

so the code ignores strings since strings don't have a method each

defined on them.



-1


source







All Articles