Iterating Over Multidimensional Arrays


#1

s = [["ham", "swiss"], ["turkey", "cheddar"], ["roast beef", "gruyere"]]

s.each do | sub_array |
 # sub_array.each do | x |    # appears to be unnecessary code in instructions
                                        # or it's the editor, more likely the editor
    puts sub_array         
                           
        
  #end    
end

=begin

The code above, (that is not commented out), should display on the console:

["ham", "swiss"]
["turkey", "cheddar"]
["roast beef", "gruyere"]
[["ham", "swiss"], ["turkey", "cheddar"], ["roast beef", "gruyere"]]

Because,

s = [["ham", "swiss"], ["turkey", "cheddar"], ["roast beef", "gruyere"]]

   s.each do | sub_array | 
     puts sub_array
   end

should iterate through the s array and puts each sub-array, right?

And the code in the lesson displays this which is correct, the code above displays the same thing ...

s = [["ham", "swiss"], ["turkey", "cheddar"], ["roast beef", "gruyere"]]

s.each do | sub_array |
  sub_array.each do | x |    
    puts x                          
  end    
end
  This code should display, which it does in the lesson:

ham
swiss
turkey
cheddar
roast beef
gruyere
[["ham", "swiss"], ["turkey", "cheddar"], ["roast beef", "gruyere"]]

Because,

s.each do | sub_array |
  sub_array.each do | x |    
    puts x                         
        
  end    
end

iterates through the s array looking at each sub-array, then the second line of code iterates through each element of each sub-array, right?
=end

Conclusion - must be the text editor/interpreter, as to why the the modified code at the top does the same exact thing as the code in the lesson?


#2

And it does appear to display this way in my console. When I loop just over the outer array, the console returns a list of sub_arrays as expected. Is it not appearing this way in yours?

This also works correctly in my console. Using the corrected code that uses nested each loops, the console displays the list of strings, followed by the multidimentional array.