ruby
  1. ruby-if-else

Ruby if-else

In Ruby, if-else statements are used to execute certain code when a condition is met. The if statement takes a Boolean expression and executes the block of code only if the expression evaluates to true. The else statement executes a block of code when the if statement is false.

Syntax

The if-else statement in Ruby has the following syntax:

if expression
  # code to execute when expression is true
else
  # code to execute when expression is false
end

Here, expression is a Boolean expression that returns either true or false.

Example

age = 20

if age >= 18
  puts "You are eligible to vote."
else
  puts "You are not eligible to vote."
end

Output:

You are eligible to vote.

Here, the if statement checks whether the age variable is greater than or equal to 18. Since the age variable is 20, the condition is true, and the code inside the if block is executed.

Explanation

In the example above, we created a variable age and set its value to 20. We then used an if-else statement to check whether the person is eligible to vote or not. The if statement checks whether the age variable is greater than or equal to 18. Since the condition is true, the code inside the if block is executed and the message "You are eligible to vote." is printed to the console.

If the age variable was less than 18, the condition would have been false, and the code inside the else block would have been executed instead.

Use

The if-else statement is used in situations where we need to execute a block of code based on a certain condition. For example, we may use if-else statements in a game to check if a player has enough points to unlock a new level. We may also use if-else statements to determine the discount a customer is eligible for based on their total purchase amount.

Important Points

  • In an if-else statement, the code inside the if block is executed only if the condition is true.
  • If the condition is false, the code inside the else block is executed.
  • If the conditions are more than one, we can use elsif statement to check multiple conditions.

Summary

The if-else statement in Ruby allows us to execute a block of code based on a certain condition. We use the if keyword to start the statement, followed by a Boolean expression. If the expression is true, the inside the if block is executed. If the expression is false, the code inside the else block is executed. The if-else statement is a powerful tool in Ruby programming and is used in many different situations.

Published on: