Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Scooter D
9,611 PointsCalling values in a multidimensional array?
I'm stuck on this problem:
s = [["dog", "bark"], ["cat", "meow"], ["sheep", "baa"]]
s.each do |x|
x.each do |y|
puts y
end
end
What is happening in the code here? I normally can visualize and depict what happens in a do/end but with this array I'm not sure.
1) Why don't I have to use brackets to call values in the array? I want to call only the the type of animal which is the first value or the array[0]. Then I want to call the second value, the sound the animal makes. I know that the values start with 0 when calling the array.
2) s.each do |x| - is this reading the whole array? or only the first value?
3) x.each do |y| - is this reading the first value? it must be because the y value is what is in puts and that is result I am looking for.
4) How does it know how to do this from |x| and |y|. It isn't like in the array that the values are labeled or defined as x and y ever. I think they would be [0] of the array and [1] of the array and brackets are never even used to call upon values in the array?
My code spits this out:
dog bark cat meow sheep baa
Any insight would greatly appreciated. Thanks!
2 Answers
Jason Seifer
Treehouse Guest TeacherHey Scott,
It might help to think of it this way:
[
["dog", "bark"],
["cat", "meow"],
["sheep", "baa"]
]
You have a big array with 3 different arrays inside it. So when you call each the first time, you're on this part of the iteration:
["dog", "bark"]
Now when you call the "each" method on THAT, you're iterating between those two elements:
puts "dog"
puts "bark"
This same thing happens for each element in both arrays, since that's what the each method does.
I know that didn't directly answer your questions but I think that may help clear it up. Let me know if you have more questions!
Scooter D
9,611 PointsDefinitely helped! Thanks Jason!