How to Create a While Loop in Ruby
When you create a while loop in Ruby, you're essentially saying "while X is true, do Y" or even "until X is false, do Y." Programmers create a while loop in Ruby in situations where they want a block of code to loop as long as a particular condition is true. There's also a converse function, the until loop, which will execute until the conditional evaluates to true. As soon as the condition is true, the until loop will end.
Instructions
-
Create a While Loop
-
1
Create a conditional statement, such as:
i = 10
while i > 0 -
2
Determine how long to run the loop. This sometimes involves setting up a variable outside of the while loop to track its progress. In this example, the while loop is used to subtract from the variable "i":
i = 10
while i > 0
# block of code containing subtraction will be added here
end -
-
3
Create the block. The block is a piece of code that gets executed every time the loop is run. In most cases, the block also modifies the condition. In this example, the intent is to subtract from the variable "i." This loop reads numbers from the keyboard and subtracts them from "i." Because of the conditional statement in the while loop, if at the end of the loop "i" is 0 or lower, the loop will end:
i = 10
while i > 0
i = i--gets.chomp.to_i
puts "i is now #{i}"
end
Create an Until Loop
-
4
Choose a while loop.
-
5
Replace "while" with "until". Though until serves the same purpose as while, in the previous example, nothing would happen as i > 0 evaluates to true as soon as the loop is run. This means the block won't execute even once. However, in some cases it's clearer.
-
6
Consider the following two examples. Using until is a more concise way of returning the result.
1.while not is_ready()
wait_until_ready()
end
2.until is_ready()
wait_until_ready()
end
-
1
Tips & Warnings
When you are reading blocks of code, be sure you don't interpret anything after the operator "#" as part of the code. If anything is written after this point, it is intended to be a guideline for programmers.
If your condition never evaluates to false, the loop will go on and on. This is a bug called an "infinite loop." Most of the time, it's an error. If it happens to you, your program will seem to stagnate endlessly. This can be stopped by hitting "Control-C".