# 12. Iterating Over Multidimensional Arrays

<Below this line, add a link to the EXACT exercise that you are stuck at.>

<In what way does your code behave incorrectly? Include ALL error messages.>
This exercise has confused me a bit. It asks “then how might we iterate over an array of arrays?” I used the method we had been using for the last few excersies to iterate an array, it worked, but then I read the instructions and apparently they want me to this in a more complicated way. However I do get message “Way to go !”
I don’t quite understand what the course wants me to do. “Call the elements sub_array.”, I wasn’t naming anything here.

```

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

s.each { |x| puts x }

``<do not remove the three backticks above>``
1 Like

Hi but the instruction aske you …

1. Iterate through .each element in the s array. Call the elements sub_array. so you do it like that

``````s.each do |sub_array|

end

``````

2. Then iterate through .each sub_array and puts out their items.

``````s.each do |sub_array|
sub_array.each do |item|
puts item
end
end
``````

@wizmarco is correct. If you wish to use a block,

write it like,

``````s.each { |x| x.each { |y| puts y } }
``````

Yes, we can nest blocks.

4 Likes

If it is not too much trouble, can you explain:

1. How Ruby reads the nest
2. Why using sub_array is unnecessary
1 Like

Not unnecessary, smart. The above is verbose and difficult to read.

For each x (sub_array) in s, it runs the nested block revealing each y in the sub_array.

I get how the sub_array thing works, and that it asked us to do that…But is there a reason we need to do it the harder way ?

since printing out all the elements of all the arrays is already done by { |x| puts x } ?

Nesting blocks is fine. Using a sub_array is not necessarily harder. It is easy to read. That is the principal concern. Elegant code is nice, and fun to write. We see the simplicity and like it. However, self-documenting code is usually a little more straight forward and readable, requiring less manual documentation.

2 Likes

Ah, got it
So not necessary but smart !

Tnx for clearing that up !

1 Like