Control Flow

While Loop in Ruby

The while loop executes a block of code while a boolean expression evaluates to true. It terminates as soon as the expression evaluates to false. The boolean expression is evaluated before each iteration.


Syntax
while booleanExpression do
    #code to be run while booleanExpression is true
    next (conditional_statement) #used to skip all code in block that follows if condition true
end

Notes

Because the boolean expression is evaluated before each iteration, the block of code executes ONLY if the booleanExpression evaluates to true. If a guarantee is needed for the block of code to run at least once, use the do-while loop.

booleanExpression results in either a true or false output. It is created using comparing operators (==, >, =, <=, !=).

There can also be multiple boolean expressions within the parentheses (booleanExpression). The boolean expressions are connected through logical operators (&&, ||, !).


Example
while distance < 100
    puts "You have not finished the race"
    distance += 10
end

puts "Race has finished!"

Add to Slack

< For Each   |   Do-While Loop >

© 2019 SyntaxDB. All Rights Reserved.