Never-ending cycle of loop


#1



https://www.codecademy.com/en/courses/ruby-beginner-en-XYcN1/2/2


The code doesn't end where it suppose to end. It keeps repeating itself infinitely. Is there something wrong with my code that might start this and how do I fix it?


i = 20
loop do
    i -= 1
    for i in 1..20
    next if i % 2 != 0
    print i
    break if i == 0
    end
end


#2

Hmm, ok...well, firstly is loop do proper syntax? :wink:
Secondly, you cannot continue to reuse the variable i in the same scope. You must use a different letter to signify that it is holding a different value.


#3

It doesn't appear in the reserved words list:

http://www.java2s.com/Code/Ruby/Language-Basics/Rubysreservedwords.htm


#4

Precisely my point! Thanks, @mtf.


#5

Thanks guys! I finally solved it! About loop do syntax, it was part of the example in the previous lesson so I'm not too sure.


#6

https://launchschool.com/books/ruby/read/loops_iterators

As stated in the earlier lesson, this is the simplest method for looping, but we must never forget it is an uncontrolled loop and will run forever if we do not install some form of control. That's the basic message in these two lessons.


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.