Control Flow

If Statement in Ruby

The if else block controls decision making by checking true/false statements resulting in different executions of code, depending on if the result is true and if the result is false.

There are three parts to the if-else block: if, elsif, and else.


Syntax
if booleanExpression
    #code to execute if booleanExpression is true
elsif booleanExpression2
    #code to execute if booleanExpression2 is true
else
    #code to execute if all previous if and elsif statements are false
end

#inverse of if statement
unless booleanExpression
    #code to execute if booleanExpression is not true
end

Notes

booleanExpression(s) are those that result in either a true or false output. They are created using comparing operators.

There can also be multiple Boolean expressions within the parentheses (booleanExpression). The Boolean expressions are connected through logical operators.

Elsif statements allow for another Boolean expression check within the overall if structure. This is optional.

Else statements result in the execution of code if the if statement (and if applicable, the subsequent else if statement(s)) do not hold true.

Nested if (else) statements are also possible and are the inclusion of another (or multiple) if statements within an if statement block.


Example
counter = 3
if (counter > 30)
    puts 'Counter is greater than 30'
elsif (counter > 20 && counter <= 30)
    puts 'Counter is between 20 and 30'
    counter = counter + 1
else
    puts 'Counter is below 20'
    counter = counter + 1
end
    

Add to Slack

< Hashes   |   Case Statement >

© 2019 SyntaxDB. All Rights Reserved.