11 why doesn't x+= 10 not add 10 then 11 then 12 to the array?


#1



https://www.codecademy.com/en/courses/ruby-beginner-en-XYcN1/2/4?curriculum_id=5059f8619189a5000201fbcb


I'm just trying to follow the logic of the below code.

  • The code takes the numbers in the array 1,2,3,4,5 and then applies x += 10 to it. When you run the code the result is 1112131415

So this code has added 10 to each number in the array, however i would have expected this code to be actually x + 10. I would have thought x += 10 would act like a counter and so increase 10 by 1 each time and therefore would add 10 to the first number, then 11 to second number, 12 to the 3rd number etc resulting in 1113151719?

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

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


#2

@benjsud,
Try using the code

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

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

with each loop you iterate over the =array=
picking 1 Element-Value at each iteration
and x += 10
actually stands for x = x + 10