-
-
Save anonymous/11218156 to your computer and use it in GitHub Desktop.
#Codecademy give me an error saying "Oops, try again. It looks like your loop doesn't print out the numbers 18 to 0." | |
#the objective is to print all even numbers 0-18 | |
#it prints it all correctly so what am I doing wrong? Thanks for any help! | |
#Codecademy - Exercise - Loops & Iterators 9/18 | |
for i in 0..18 | |
next if i % 2 == 1 | |
puts i | |
end |
Note that for
loops aren't considered very Ruby-esque; using Range#each
instead is much better.
Also, if the exercise text says "the numbers 18 to 0", you need to reverse your range.
18.downto(0).each do |i|
next if i.odd?
puts i
end
Your code runs perfect. But I think there is a problem with Codecademy
It's possible I'm missing a requirement in the exercise. Here's the exercise in full:
Next!
The next keyword can be used to skip over certain steps in the loop. For instance, if we don't want to print out the even numbers, we can write:
for i in 1..5
next if i % 2 == 0
print i
end
In the above example, we loop through the range of 1 through 5, assigning each number to i in turn.
If the remainder of i / 2 is zero, we go to the next iteration of the loop.
Then we print the value of i. This line only prints out 1, 3, and 5 because of the previous line.
Instructions
Add a line to your loop before your print statement. Use the next keyword so that you skip to the next iteration if the number i is odd.
Use the example above for help, but remember that the example above skips even numbers.
That can't be the entire exercise, can it? It doesn't mention that it wants the range 18 down to 0.
Anyway, if they use print
instead of puts
they might expect the actual output to be "181614121086420"
(puts
adds a newline).
18.downto(0).each do |i|
next if i.odd?
print i # Note the use of print
end
Or, using a for
loop as they seem to want (although it's not very idiomatic Ruby) and modulo:
for i in 18.downto(0)
next if i % 2 == 1
print i # Note the use of print
end
That worked! Thanks a bunch!
BTW, this is ruby. smh