Try it out, Loops and Iterators, #12


Hey so I get what to put to make the code work, but I dont understand what the code is printing out. In a real work scenario, what would this help us do, is this what it always looks like?
Thanks you

odds = [1,3,5,7,9]

Add your code below!

odds.each do|x|
print "#{x}"


Ho @qgreen ,

Following is an enhanced version of the code, intended for illustrative purposes. It will not pass for this exercise, but it may help clarify what is happening here.

odds = [1,3,5,7,9]
# Add your code below!
odds.each do |x|
  x *= 2
  print "The answer is #{x}\n"

This loop header assigns each item in the odds array, in turn, to x as the loop iterates ...

odds.each do |x|

Inside the loop, this line includes the format specifier, #{x}, within a string ...

print "The answer is #{x}\n"

In the actual output, the value of x replaces the format specifier, as a part of the output string.

The above example will execute correctly in a Ruby interpreter, but will not pass Codecademy's test, if submitted, because it adds extra information to the output.


I mean for a job, what is an example of a time you would use this, in a real design scenario?


You probably would not use this exactly as is for any real design scenario. However, a programmer would likely encounter situations that require looping through each item in an array, performing a test on the item, and then taking an action based on the outcome of that test.


its aimed more toward building a foundation with ruby that will help you diagnose and solve problems that you may be confronted with while coding in the future.


I'm curious to know why wouldn't it be x=2 or x=2 it believe it makes more sense. Since this way in human terms means x equals times 2; or 2 times. can you please explain.


Hi @jtejada61 ,

Codecademy wants you to multiply each odd number in the array by 2, and then display the result. If you use x = 2, it will just display 2 for each number, without regard to the original value of the item. You could use x = x * 2, if you want. But x *= 2 is a shortcut that many programmers use. Once you get accustomed to operators such as +=, -=, *=, and /=, you may find them more convenient and easier to read than the longer alternative.


Got it! thanks for the reply. Are you a beginner like myself; or have you been doing this for a while? I recently decided to step into the coding world to learn as much as i can.. Hopefully it leads me down an awsome path! :sunglasses: