In Ruby have different types loops which are used to perform different operations and are listed below.
- While
- Do/While loops
- until loops
- For loops
While
While loop evaluates the given parameter into the Boolean value which can be either true or false. In which boolean expression get false result then while loop will doesn't execute and execution will continuous after the while loop. The snippet below demonstrates to executing the while statement as shown below.
[ruby]
x = gets.chomp.to_i
while x >= 0
puts x
x = x - 1
end
puts "Done!"
[/ruby]
Result
By running the above code in command prompt, the output can be obtained as shown in the image below.
Do/While
In Ruby Loop Do/while is same as the while loop but only difference is with in the loop code and will be executed only once which prior to the conditional check to verify if the code executed. Conditional check placed at the end of the do while loop which is exactly opposite to the beginning of the loop. The code below demonstrates the Do/While loop as shown below.
[ruby]
loop do
puts "Do you want to do that again?"
answer = gets.chomp
if answer != 'Y'
break
end
end
[/ruby]
Result
By running the above code in command prompt, the output can be obtained as shown in the image below.
until
In Ruby Loop Until loop is opposite to the while loop in order to phrase the problem user need to substitute it in a different way the code below demonstrates the until loops as shown below.
[ruby]
x = gets.chomp.to_i
until x < 0
puts x
x -= 1
end
puts "Done!"
[/ruby]
Result
By running the above code in command prompt, the output can be obtained as shown in the image below.
For
For loops can be used on collection of elements which consist definite end and finite number of elements which starts with reserved word and follows variables in the reserved word and some collection of element. The code below demonstrates the for loops as shown below.
[ruby]
x = gets.chomp.to_i
for i in 1..x do
puts i
end
puts "Done!"
[/ruby]
Result
By running the above code in command prompt, the output can be obtained as shown in the image below.