Iterating over a 2-D array in Ruby

I’ve had trouble understanding how nested .each loops work, so I did some investigating and expanded upon (and hopefully clarified) an example from Codeacademy. 

Let’s start with a 2-D array.

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

The instructions were to iterate over s in such a way that we don’t print out each element, like ["ham", "swiss"], but each element within each element, so we get a list of all the meats and cheeses within s.

First, let’s do the opposite and print out each element in the 2D array like [“ham”, “swiss”]. To do that, we use only one .each loop. In this case, puts is called only 3 times. We can prove this by marking the puts statement with “>>>”.

s.each do |x|
   puts “>>>”, x
   end

>>>
ham
swiss
>>>
turkey
cheddar
>>>
roast beef
gruyere

Now let’s use nested .each iterators/loops to iterate through a 2D array (to actually go inside each element within each element). With nested .each iterators we are calling puts 6 times. We can show this again by marking the puts statement with “>>>”.

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

s.each do |x|
      x.each do |y|
      puts “>>>”, y
      end
end

>>>
ham
>>>
swiss
>>>
turkey
>>>
cheddar
>>>
roast beef
>>>
gruyere

To summarize, the difference between one .each loop and nested .each loops is the latter permeates the dimensions of the array; it prints the elements within each element separately, calling puts twice the number of times.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s