The .each iterator


#1

https://www.codecademy.com/en/courses/ruby-beginner-en-XYcN1/2/4?curriculum_id=5059f8619189a5000201fbcb
there's not a problem to be solved in this lesson, just wanted to know if anybody can explain more how the code in the example came up with this answer?
1112131415[1, 2, 3, 4, 5]

Replace this line with your code.


#2

Let's add a space between numbers to make it clearer:

array = [1,2,3,4,5]

array.each do |x|
  x += 10
  print "#{x} "
end

And now the output is:

11 12 13 14 15 
=> [1, 2, 3, 4, 5]

As you know each iterates through values. So our first value (x) is 1. We add 10 to 1 and we get 11. The next value is 2, after addition it becomes 12... That's clear, right?

Why there is a [1, 2, 3, 4, 5] in the output? Ruby returns the value of the last evaluated expression. In the normal environments, the return value of the last evaluated expression is marked by the => (or similar) indicator.


#3

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