 # 12. Try it out - Are there two ways to do this?

Okay, so in the example it says there are two ways to loop.

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

# one way to loop

numbers.each { |item| puts item }

# another way to loop

numbers.each do |item|
puts item
end

The lesson then asks us to:

Use the .each method on the odds array to print out double the value of each item of the array. In other words, multiply each item by 2.

I understand how to write the code for the second example (# another way to loop) in this exercise.

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

odds.each do |x|
x *= 2
print “#{x}”
end

But I don’t understand if it is possible, or how to make the first example ( # one way to loop) work.

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

odds.each { |x| print “#{x}” }

I have tried:

odds.each { |x| x *= 2 print “#{x}” }

and

odds.each { |x| print “#{x}” } x *=2

but neither work. where do you put in the bit to make it multiply, and how do you write it for the first example of the loop (if it’s even possible)?

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

odds.each{ |x| puts "#{x*2}" }
``````

This will work Make sure to use puts instead of print for that block.

1 Like

Ahh, I see! Thanks very much!

Hello guys!
The mine did not work I used the code bellow:

odds = [1,3,5,7,9]
odds.each{ |x| puts “#{x*2}” }
x *= 2
print “#{x}”
end

1 Like

I found part 12 of this lesson a little confusing too. In part 11 they showed us two different ways to make a loop.

1. object.each { |item| # Do something }

2. object.each do |item| # Do something end

Now in part 12 they show us both ways to make a loop in the example, but you have to choose which one you will use. The code you posted has parts of both ways mixed together.

To complete the assignment there are two ways you can write your code.
.
You can write your code like this:

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

odds.each{ |x| print "#{x*2}" }
``````

or you can write you code like this:

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

odds.each do |x|
x *= 2
print "#{x}"
end
``````

I hope this helps!

1 Like

No need to calculate again:
x *= 2
Or to print again:
print “#{x}”

And because you used { } at the odds.each, you dont need the end at final of code.

Good luck!

Hi the correct answer is below because the instructions specifically ask you to user print not puts
odds = [1,3,5,7,9]
odds.each { |odds| print “#{odds*2}” }
end

odds = [1,3,5,7,9]
odds.each do |x|
print x * 2
end