Ruby’s elsif keyword adds another condition to an if statement. Ruby tests conditions in order, executes the first successful branch, and ignores the remaining branches. section 6.1.1
A cascading conditional can:
- Contain any number of elsif clauses. section 6.1.1
- End with else, which runs when every preceding condition is false. section 6.1.1
- Return nil when no condition succeeds and no else branch exists. section 6.1.1
Classifying a number
x = 1 if x < 0 "negative" elsif x > 0 "positive" else "zero" end # => "positive" section 6.1.1
if condition1
# code executed if condition1 is true
elsif condition2
# code executed if condition1 is false
# and condition2 is true
elsif condition3
# code executed if neither condition1
# nor condition2 is true, but condition3 is
end
Use this branching template to place mutually exclusive conditions in priority order. section 6.1.1
