Skip to content

Instantly share code, notes, and snippets.

Created April 23, 2014 14:45
Show Gist options
  • Save anonymous/11218156 to your computer and use it in GitHub Desktop.
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
@p0wder
Copy link

p0wder commented Apr 23, 2014

BTW, this is ruby. smh

@tobiasvl
Copy link

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.

@tobiasvl
Copy link

18.downto(0).each do |i|
  next if i.odd?
  puts i
end

@p0wder
Copy link

p0wder commented Apr 23, 2014

Your code runs perfect. But I think there is a problem with Codecademy

@p0wder
Copy link

p0wder commented Apr 23, 2014

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.

@tobiasvl
Copy link

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

@p0wder
Copy link

p0wder commented Apr 23, 2014

That worked! Thanks a bunch!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment