What is going on?


#1



https://www.codecademy.com/en/courses/ruby-beginner-en-F3loB/2/3?curriculum_id=5059f8619189a5000201fbcb#


There are no error messages. I just don't understand the purpose of this code-- what is this achieving?

My results:
ham
swiss
turkey
cheddar
roast beef
gruyere
[["ham", "swiss"], ["turkey", "cheddar"], ["roast beef", "gruyere"]]


s = [["ham", "swiss"], ["turkey", "cheddar"], ["roast beef", "gruyere"]]
s.each {|sub_array| 
    sub_array.each {|d| puts d}
}


#2

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

You have created s, s represents a three dimensional array (pretty cool eh?)

s.each # Let's talk about .each, It iterates, or cycles through everything we tell it to. In this case s

Now comes the block ( { } or do/end ) and its compadre, block argument represented by | | pipes
do or { can begin a block. I recommend using do right now

PHEW!
Lets see where we are
s.each do |sub_array| #do begins our block, think of blocks as a way of "pinching" code for now, This block takes everything from s and stores it inside our block as the argument |sub_array|
Remember! we are still within the crab pincers { } or do/end of the block. We live in its world now. We gave it the data from s and its calling it sub_array now because you told it to (go you!)

Now then

s.each do |sub_array|
sub_array.each do |item| puts item

We are calling the strings inside the sub_array, item (because we created the block argument |item|) now we want the computer to puts item to screen. the computer recognizes those strings contained in the sub_array, you told (block argument | |) to call those "strings" |item| and now it will

INSIDE THE BLOCK, ONLY IN THE BLOCK
end
end

Once you end the blocks the |item| no longer represents the strings held inside the 3d array s

It has lived out its glory days in the block. Try calling item after you have properly ended your block to see what I mean.

Let's see it all now!

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

s.each do |sub_array|
sub_array.each do |item| puts item
end
end

At its core the function of this code was to display the data contained within the array using puts
You created an array, iterated through its content, temporarily stored it inside a block argument, and puts that argument.

I hope that helps!


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.