From: "Jesús Gabriel y Galán" Date: 2012-10-03T16:19:44+09:00 Subject: Re: how to read arrary with an array On Tue, Oct 2, 2012 at 8:44 PM, Richard D. wrote: > thanks for the replies, especially the thorough one from Jesus. What > you explained was what I was thinking. I was expecting nil outputs. > > What I can't seem to figure out is how come I'm getting outputs between > these codes: > > array1 = [['a','b'],[1, 2],['x','y']] > > array1.each do |ray| > puts ray[0] #output a1x (expected and wanted) > end > > puts "=======" > > array1.each do |ray| > puts ray[1] #output b2y (expected and wanted) > end > > puts "=======" #versus# > > array1.each do |ray| #four outputs of a, b1, 2x, y > puts ray[0] > puts '****' > puts ray[1] > end > > I was assuming I would get the same outcome. I'm not seeing difference > other than being repeative between the two codes paragraphs(?). I > suspect my lack of understanding my lie I'm not really sure what you expected in the third case, but let's see step by step what this does. The method each iterates over your array, passing each element in turn to the block. For example: array = [1,2,3] array.each do |element| p element end This iterates over the array passing 1, then 2, then 3 to the block. The block receives that value in the element variable, which is just printed. array1 = [['a','b'],[1, 2],['x','y']] array1.each do |ray| p ray puts ray[0] puts '****' puts ray[1] end In this case, the array has 3 elements. Each time around the loop the "ray" variable will contain one of the elements. The first time, ray will be ['a','b']. So when you print ray[0] it prints 'a' and when you print ray[1] it prints 'b'. The second time, ray will be [1,2]. The third time, ray will be ['x','y']. This explains the behaviour you see. Jesus.