Elsif Statement in Ruby



In this tutorial, we will learn about elsif statements in Ruby. We will cover the basics of conditional execution using if-elsif-else statements.


What is an Elsif statement

An elsif statement is a conditional statement that allows multiple conditions to be tested sequentially. It provides a way to execute different code blocks based on different conditions.


Syntax

The syntax for the elsif statement in Ruby is:

if condition1
    # Code block to execute if condition1 is true
elsif condition2
    # Code block to execute if condition2 is true
else
    # Code block to execute if none of the conditions are true
end

The elsif statement evaluates the specified conditions in order. The first condition that is true will have its code block executed; if none of the conditions are true, the code block inside the else statement is executed.

Flowchart of Elsif Statement


Example 1: Checking if a Number is Positive, Negative, or Zero

We can use an elsif statement to check if a given number is positive, negative, or a zero.

For example,

  1. Declare a variable num.
  2. Assign a value to num.
  3. Use an if-elsif-else statement to check if num is positive, negative, or zero.
  4. Print a message indicating whether num is positive, negative, or zero.

Ruby Program

num = -5
if num > 0
    puts "#{num} is positive."
elsif num < 0
    puts "#{num} is negative."
else
    puts "#{num} is zero."
end

Output

-5 is negative.


Example 2: Checking the Grade of a Student

We can use an elsif statement to prepare the grade of a student based on the marks.

For example,

  1. Declare a variable marks.
  2. Assign a value to marks.
  3. Use an if-elsif-else statement to check the grade based on the marks.
  4. Print a message indicating the grade.

Ruby Program

marks = 85
if marks >= 90
    puts 'Grade: A'
elsif marks >= 80
    puts 'Grade: B'
elsif marks >= 70
    puts 'Grade: C'
elsif marks >= 60
    puts 'Grade: D'
else
    puts 'Grade: F'
end

Output

Grade: B


Example 3: Checking the Temperature Range

We can use an elsif statement to prepare a descriptive message about the temperature of the day.

For example,

  1. Declare a variable temperature.
  2. Assign a value to temperature.
  3. Use an if-elsif-else statement to check the range of the temperature.
  4. Print a message indicating the temperature range.

Ruby Program

temperature = 75.5
if temperature > 100
    puts "It's extremely hot."
elsif temperature > 85
    puts "It's hot."
elsif temperature > 60
    puts "It's warm."
elsif temperature > 32
    puts "It's cold."
else
    puts "It's freezing."
end

Output

It's warm.