Conditional statements in Ruby
The main purpose of conditional statements in Ruby is to allow programs to make decisions based on conditions.
Ruby provides the following conditional statements:
- if statement
- if-else statement
- if-elsif-else statement
- Nested if statement
- unless statement
- case-when statement
1. if statement
The if statement executes a block of code only when the given condition is true.
Syntax:if condition
statements
end
2. if-else statement
The if-else statement is used when we want to execute one block of code if the condition is true and another block if the condition is false.
Syntax:if condition
statements
else
statements
end
3. if-elsif-else statement
The if-elsif-else statement is used when we need to check multiple conditions.
Syntax:if condition1
statements
elsif condition2
statements
else
statements
end
4. Nested if statement
An if statement written inside another if statement is called a nested if statement. It is used to check one condition inside another condition.
Syntax:if condition1
if condition2
statements
end
end
5. unless statement
The unless statement is similar to the if statement, but it executes the code when the condition is false.
Syntax:unless condition
statements
end
Example: marksgrade.rb
print("Enter Student Marks : ")
marks = gets.chomp.to_i
if marks >= 90
puts "Grade A"
elsif marks >= 70
puts "Grade B"
elsif marks >= 40
puts "Pass"
else
puts "Fail"
end
Output:
ruby marksgrade.rb
Enter Student Marks : 75
Grade B
6. case-when statement
The case-when statement is used to select one option from multiple choices. It is similar to the switch statement in other programming languages.
Syntax:case variable
when value1
statements
when value2
statements
else
statements
end
Example: dayname.rb
print "Enter a day number(1-7) : "
day = gets.chomp.to_i
case day
when 1
puts "Monday"
when 2
puts "Tuesday"
when 3
puts "Wednesday"
when 4
puts "Thursday"
when 5
puts "Friday"
when 6
puts "Saturday"
when 7
puts "Sunday"
else
puts "Invalid day"
end
Output:
ruby dayname.rb
Enter a day number(1-7) : 5
Friday