Iterating Over Multidimensional Arrays in Ruby
Your block parameters deconstruct the array as follows:
The enumerator generated by :each
yields each element of the outer array in sequence, and then applies the pattern matching based on the structure of the block parameters. So in the first iteration, you have [1,2,3]
yielded to the block, which is then mapped to numbers = 1
and colors = 2
. 3
is ignored because it doesn't fit the pattern.
If you only want to display one sub-array, you don't need iterate over the whole array- just grab the required element by the index (if you know what the index is):
things[1].each {|color| ... }
Or, you can assign it to a variable in a similar way. As long as you know the colors will always be in the second position, you can do this:
_, colors = *things
colors.each {|color| ... }
Clayton
Updated on June 04, 2022Comments
-
Clayton almost 2 years
I'm going over iteration within multidimensional arrays in Ruby on Codecademy and came across a question I can't seem to find the answer to. So, in their example, they show that a multidimensional array can be iterated using the following code:
things = [[1,2,3], ["red", "blue"]] things.each do |sub_array| sub_array.each do |item| puts item end end
This prints out the values of both sub_arrays. However, if I only want to display one sub_array, how would I go about that? I have tried the following code but I'm getting an undefined method `each' for 2:Fixnum error.
things = [[1,2,3], ["red", "blue"]] things.each do |numbers, colors| colors.each { |item| puts item } end
So, I guess my question is why my code is not functioning correctly and how I would go about printing out only the array at index 1?