12. Iterating over Multidimensional arrays


#1

Here's my code for Lesson 7.12:

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

s.each { |sub_array| puts sub_array}
sub_array.each { |item| puts item}

It tells me "Way to go!" and start the next lesson, but I also have an error:

undefined local variable or method 'sub_array' for #

I'm not sure what's going on.


#2

This error is caused by the variable being out of block scope. We need to nest the inner iteration inside the block. Consider:

s.each { |x| x.each { |n| puts n }}

=begin
ham
swiss
turkey
cheddar
roast beef
gruyere
=end

We can write a more readable version with do:

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

In each case variables maintain block scope.

Supplemental

We can print the element lists on single lines:

s.each do | x |
  puts ''
  x.each do | y |
    print "#{y} "
  end
end
puts ''

=begin
ham swiss 
turkey cheddar 
roast beef gruyere 
nil
=end

#3

this code was correct I justed wanted to know why I had to put end twice for the code to acceptable?

s.each do |sub_array|
sub_array.each do |i|
puts i


#4

do requires an end. Your code has two do's so requires two end's.