In this tutorial, we will learn about elsif statements in Ruby. We will cover the basics of conditional execution using if-elsif-else statements.
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.
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.
We can use an elsif statement to check if a given number is positive, negative, or a zero.
For example,
num
.num
.num
is positive, negative, or zero.num
is positive, negative, or zero.num = -5
if num > 0
puts "#{num} is positive."
elsif num < 0
puts "#{num} is negative."
else
puts "#{num} is zero."
end
-5 is negative.
We can use an elsif statement to prepare the grade of a student based on the marks.
For example,
marks
.marks
.marks
.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
Grade: B
We can use an elsif statement to prepare a descriptive message about the temperature of the day.
For example,
temperature
.temperature
.temperature
.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
It's warm.