0
0
Rubyprogramming~5 mins

If, elsif, else statements in Ruby

Choose your learning style9 modes available
Introduction

If, elsif, else statements help your program make choices. They let your code do different things based on conditions.

Deciding what message to show based on user input.
Checking if a number is positive, negative, or zero.
Choosing a discount based on the amount spent.
Responding differently to different weather conditions.
Validating form data and giving feedback.
Syntax
Ruby
if condition
  # code to run if condition is true
elsif another_condition
  # code if the first condition is false but this one is true
else
  # code if all above conditions are false
end

The if starts the check.

You can have zero or more elsif parts.

The else part is optional and runs if no conditions match.

Examples
This checks if age is 18 or more. If yes, it prints a message. Otherwise, it prints a different message.
Ruby
if age >= 18
  puts "You can vote."
else
  puts "You are too young to vote."
end
This example shows multiple checks. It prints different grades based on the score.
Ruby
if score >= 90
  puts "Grade A"
elsif score >= 80
  puts "Grade B"
else
  puts "Grade C or below"
end
You can have just an if without elsif or else. It runs code only if the condition is true.
Ruby
if logged_in
  puts "Welcome back!"
end
Sample Program

This program asks for your age and tells you if you are a child, teenager, or adult using if, elsif, else statements.

Ruby
puts "Enter your age:"
age = gets.to_i

if age < 13
  puts "You are a child."
elsif age < 20
  puts "You are a teenager."
else
  puts "You are an adult."
end
OutputSuccess
Important Notes

Remember to end the if block with end.

Conditions must be true or false values.

Indent your code inside the if, elsif, else blocks for readability.

Summary

If statements let your program choose what to do.

Use elsif for multiple checks.

else runs when no conditions match.