FAQ: Data Structures - Iterating Over Multidimensional Arrays

This community-built FAQ covers the “Iterating Over Multidimensional Arrays” exercise from the lesson “Data Structures”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Learn Ruby

FAQs on the exercise Iterating Over Multidimensional Arrays

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

Hello guys, for this chapter i did this:

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

s.each { |x| puts x}

How come it’s wrong?

1 Like

Here is what I did:
s = [[“ham”, “swiss”], [“turkey”, “cheddar”], [“roast beef”, “gruyere”]]
sub_array = 0
s.each do |x| sub_array = x
sub_array.each do |y| puts y end

Only question… Huh?


This was the first head scratcher lesson that I had. This was the code I wrote to satisfy the scenario:

s = [[“ham”, “swiss”], [“turkey”, “cheddar”], [“roast beef”, “gruyere”]]
s.each do |sub_array| # This grabs each sub array inside s and assigns it to sub_array
sub_array.each do |y| # For each of the elements in the sub_array addign it to y
puts y # prints each element


@justjosh42 Thanks for explaining what the code does, step by step. Very helpful!

This took me a sec to figure out but after a handful of attempts, I was able to condense it into one line.

This first attempt here is how I got to list all of the words but they were out of order (0, 0, 0, 1, 1, 1). This satisfied the criteria but it only felt half correct since I wanted to list out what I called ingredients in sequential order (0, 1, 0, 1, 0, 1).

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

s.each { |sub_array| puts sub_array[0]}
s.each { |sub_array| puts sub_array[1]}

This second answer satisfies the criteria listing the ingredients in sequential order. After breaking s into subarrays I broke the subarray into individual ingredients then puts each ingredient so they list out (0, 1, 0, 1, 0, 1).

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

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


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

s.each do |nested_array| #goes through each array in the s array, with placeholder “nested_array”
nested_array.each do |ingredient| #goes through items in nested array’s and calls it “ingredient”
puts ingredient #then puts out all of those “ingredient” items to the console

1 Like

Here below, was my lucky/thoughtful guess which turned out to yield the correct results in the console, even though this wasn’t what the lesson was looking for.

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

s.each { |x, y| puts x }
s.each { |x, y| puts y }

Can anyone explain why this works? Does it have something to do with multidimensionals and x, y? Thank you!

Let’s first examine the output…

#|x, y| => x

roast beef

#|x, y| => y


When we specify a pair of block parameters, Ruby would appear to match them up with values in the nested array. It’s almost like saying, Each value pair in s. That’s what we observe.

The why and wherefore will obviously go much deeper than this.

A single block parameter will issue forth each nested array, in turn, and as an array. Doubling up the parameter must be a signal to Ruby to unpack the nested arrays as they are encountered and render only the values to x and y.

Below we iterate the array and iterate its nests, putting one value at a time.

s.each { |x| x.each { |y| puts y } }
roast beef
1 Like

Just playing around a bit. Seems Ruby has some rather loose rules regarding unpacking. At least with regards to matching the number of values.

z = [1,2,3,4,5,6]
z.each { |a,b,c,d,e,f,g,h,i| print "a: #{a}  ", "i: #{i}\n"}
puts "*****"
y = [1]
a, b, c = y
puts "a: #{a}", "b: #{b}", "c: #{c.class}"
a: 1  i: 
a: 2  i: 
a: 3  i: 
a: 4  i: 
a: 5  i: 
a: 6  i: 
a: 1
c: NilClass

Hi guys, I can’t figure out why it’s not working with this code :

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

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

With the other way, it’s perfectly works :

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

s.each do |sub_array|
  sub_array.each do |sub_sub_array|
  puts sub_sub_array

Thanks for your help !

In the above the blocks are closed around the block parameter and missing their code.

s.each { |x| 
  x.each { |y|
    puts y

It works ! Thank you so much :slight_smile:

1 Like

Hi all! This is a 3 part question. I think I’m making quite a few mistakes, and I’m not understanding/missing a key component. This is my first foray into coding and on this forum. Please let me know if there is anyway I can convey my questions better on the forum. Thank you.

Question 1
I would like to put only a list of the cheeses
s = [[“ham”, “swiss”], [“turkey”, “cheddar”], [“roast beef”, “gruyere”]]

Is it possible to pull up a list of only the y of |x,y| using something like below; I got no output when executed? Or is the |x,y| assigning variables but not indicating indicies?
s.each { |sub_array| sub_array.each { |x,y| puts y}}

There was a prior example in a lesson that showed we could do this.
family = {“Homer” => :dad", “Marge” => “mom”, “Bart” => “son”, “Lisa” => “daugter”}
family.each {|x,y| puts “#{y}”}
==> dad
So I tried
s.each { |sub_array| sub_array.each { |x,y| puts “#{y}”}}
But it again gave me an entire list of both meat and cheeses

Because [0] and [1] refers to indexes, it made sense that list of values can be pulled up via:
or (putting entire meat list with [0], or entire cheese list with [1])
s.each { |sub_array| puts sub_array[0]}
s.each { |sub_array| puts sub_array[1]}

Question part 2
Is it possible to puts an individual cheese of a sub array, in this case for example [[“ham”, “swiss”], etc] other than using puts s[0][1]?

Question part 3

When assigning key value pairs, is it possible to input a value to output the key? Or is the is it not really treated like indices?

Thank you.

Please post a link to the exercise so I can test in the same context.

In the meantime, consider,

s = [['ham', 'swiss'], ['turkey', 'cheddar'], ['roast beef', 'gruyere']]
s.each {|x, y| puts x; puts y}
roast beef
t = []
u = []
s.each {|x, y| t << x; u << y}
puts t
puts u
["ham", "turkey", "roast beef"]
["swiss", "cheddar", "gruyere"]


Thank you, your explanation helped clear it up for me.

I think I was treating it like an array within an array within an array

1 Like

Their explanation was the first time it clicked for me too on this one. Why was the code so much easier than the sub_array stuff they were trying to get you to do? That just confused me until I saw this post.

Hi everyone.

I don’t understand why this works: s.each { |sub_array| sub_array.each { |y| puts y}}

I’m trying to explain to myself what I’ve asked it to do, but I’m lost. Something like this: take the s array and for each sub_array iterate over each element of that and put string y? How does it know to put string x?


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

s is an array of arrays i.e. each element of this array is an array.

s.each {|sub_array| ...} iterates over each element of the array and in every iteration the element is assigned to the variable sub_array ( Remark: There is nothing special about the name sub_array. You could have picked a different name for the variable e.g. s.each {|x| ...} or some other name).

The each method passes in one element at a time to the block and assigns it to the parameter sub_array. In other words, in the first iteration, sub_array will be assigned ["ham", "swiss"]. In the second iteration, sub_array will be assigned ["turkey", "cheddar"] and so on.

sub_array.each {|y| puts y} iterates over each element of the sub_array and assigns it to a variable y. Again, nothing special about the choice of name of y.

Basically, this is what is happening:

  • The first iteration of the outer each assigns the array ["ham", "swiss"] to the variable sub_array. Then, the inner each iterates over sub_array. In the first iteration of the inner each, y will be assigned the string "ham" and puts will show the string on screen. Then the second iteration of the inner each, y will be assigned the string "swiss" and will be shown on screen. Since there are no more elements in sub_array, so the inner each is finished.

  • Now, we run the second iteration of the outer each and assign the array ["turkey", "cheddar"] to sub_array. Then, just as above the inner each iterates over this sub_array and so on …