(Lesson 12) I can clear it, but I don't understand it


#1



Lesson 12: Iterating over multidimensional arrays

I do the exercise as instructed, and the code does run correctly, but I fail to understand the point of the lesson. Any clarification would be greatly appreciated!


#This solution:
s.each { |sub_array|
    sub_array.each { |y|
    puts y}
}

#Returns every element in the array (and allows me to continue). However:

#This solution
s.each { |x|
    puts x
}
#Returns the exact same result (and allows me to continue to the next lesson).
#So, why go through the trouble of nesting one .each method in the other?


#2

Both examples above do output the same,

ham
swiss
turkey
cheddar
roast beef
gruyere

However,to demonstrate where nesting is useful, consider the following:

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

which outputs,

ham swiss 
turkey cheddar 
roast beef gruyere

See how a single block will not make this output possible?


#3

Ah, I see. So, the first block tells it to space the output by individual arrays, while the second block is the output?

That makes more sense. Thanks for your time!


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.