12. Iterating Over Multidimensional Arrays


#1



https://www.codecademy.com/en/courses/ruby-beginner-en-F3loB/2/3?curriculum_id=5059f8619189a5000201fbcb


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 }


#2

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

#3

@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

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

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


#5

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.


#6

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 } ?


#7

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.


#8

Ah, got it :slight_smile:
So not necessary but smart !

Tnx for clearing that up !


#10