Step 12: Loops


Loops

Take a look at the code below:

number = 0
puts(number)
number = number + 1
puts(number)
number = number + 1
puts(number)
number = number + 1
puts(number)
number = number + 1
puts(number)

puts("The End")

#=> 0
#=> 1
#=> 2
#=> 3
#=> 4
#=> The End

In this example we are repeatedly increasing a number and then printing it out. This gets very tiresome, especially in programs where we might want to do something reptetively 1,000 or even 1,000,000 times. Would we really have to write 1,000,000,000,000 lines of code to accomplish this?

Luckily, in Ruby, we can instead do this:

number = 0
while number < 5
    puts(number)
    number = number + 1
end
puts("The End")

#=> 0
#=> 1
#=> 2
#=> 3
#=> 4
#=> The End

The program above does the exact same thing as the previous example, but with much less code.

Here is another example:

while 1 < 2
    puts("this is the song that doesn't end")
end

Above we have an example of an "infinite loop". Since 1 is always less than 2, this code will run forever printing to the screen infinitely. Trying pasting that code into repl.it and watch it freak out! You have to hit the stop button, or else it will just run and run and run.

Here is the opposite example:

while 100 < 50
    puts("this will never print")
end

In the code above, 100 < 50 is never true, so the line puts("this will never print") will never run, and nothing will be printed to the screen.