0
0
RubyHow-ToBeginner · 3 min read

How to Use elsif in Ruby: Syntax and Examples

In Ruby, elsif is used to check multiple conditions after an initial if statement. It allows you to run different code blocks depending on which condition is true, and it must be placed between if and else.
📐

Syntax

The elsif keyword is used after an if condition to test additional conditions if the previous ones are false. You can have multiple elsif clauses, and optionally end with an else for the default case.

  • if: starts the condition check
  • elsif: checks another condition if the previous if or elsif was false
  • else: runs if none of the above conditions are true
ruby
if condition1
  # code if condition1 is true
elsif condition2
  # code if condition2 is true
elsif condition3
  # code if condition3 is true
else
  # code if none of the above are true
end
💻

Example

This example shows how to use elsif to check a number and print if it is positive, negative, or zero.

ruby
number = 5

if number > 0
  puts "The number is positive"
elsif number < 0
  puts "The number is negative"
else
  puts "The number is zero"
end
Output
The number is positive
⚠️

Common Pitfalls

One common mistake is using multiple if statements instead of elsif, which causes all conditions to be checked independently instead of stopping at the first true one. Another mistake is forgetting to use end to close the block.

ruby
wrong:
if x > 10
  puts "Greater than 10"
end
if x > 5
  puts "Greater than 5"
end

right:
if x > 10
  puts "Greater than 10"
elsif x > 5
  puts "Greater than 5"
end
📊

Quick Reference

KeywordPurpose
ifStart a condition check
elsifCheck another condition if previous was false
elseRun if no conditions are true
endClose the conditional block

Key Takeaways

Use elsif to check multiple conditions in one block.
Only the first true condition's code runs; others are skipped.
Always close your if block with end.
Avoid using separate if statements when elsif is needed.
You can have many elsif clauses between if and else.