Conditionals: if, elsif, else
Prerequisites: Operators
A conditional lets your program make a decision: run some code only when a condition is true.
Real-world analogy: "If it's raining, take an umbrella; otherwise, wear sunglasses."
Syntax
if condition
# runs when condition is true
elsif other_condition
# runs when the first was false and this one is true
else
# runs when none of the above were true
end
Note the spelling: elsif, not else if or elif.
Example
temperature = 18
if temperature > 25
puts "It's hot"
elsif temperature > 15
puts "It's pleasant"
else
puts "It's cold"
end
Expected output
It's pleasant
Ruby checks each condition from top to bottom and runs only the first
branch that matches. 18 > 25 is false, 18 > 15 is true, so it
prints "It's pleasant" and skips the rest.
if returns a value
Because everything in Ruby is an expression, you can assign the result
of an if:
age = 20
status = if age >= 18
"adult"
else
"minor"
end
puts status
adult
For short choices like this, the ternary operator is common:
status = age >= 18 ? "adult" : "minor".
Common mistakes
- Writing
else if— Ruby treats that as a nestedifthat needs its ownend, which usually ends in a syntax error. - Putting conditions in the wrong order.
if score > 50beforeif score > 90means the second branch can never run.
Practice
Write a program that stores an age and prints adult if it's 18 or
over, teen if it's 13 to 17, and child otherwise.
Show solution
age = 15
if age >= 18
puts "adult"
elsif age >= 13
puts "teen"
else
puts "child"
end
teen