Conditions
| if and else | |
| unless modifier | |
| elsif chains | |
| case-when |
if and else
The if statement runs a block only when its condition holds, and else covers everything that fails the check. Close the branch with the end keyword.
age = 20
if age >= 18
puts "adult"
else
puts "minor"
end
adult
unless modifier
unless is if turned upside down: the line runs only when the condition is falsy. As a one-line modifier at the end, it reads like plain advice and avoids a negation mark.
logged_in = false
puts "guest" unless logged_in
guest
elsif chains
When several outcomes exclude each other, chain elsif branches between if and else. Only the first block with a true condition runs, so order the checks from the strictest to the loosest one.
Note the spelling: Ruby writes elsif with one e in the middle.
score = 85
if score >= 90
puts "excellent"
elsif score >= 70
puts "good"
else
puts "needs work"
end
good
case-when
case compares one value against a list of candidates and runs the first match. Each when names a candidate, and else catches anything unmatched at the bottom.
role = :admin
case role
when :admin
puts "full access"
when :guest
puts "read only"
else
puts "unknown"
end
full access
Next: Loops
Article author: Arthur Isaev