Ruby offers the expected if
and else
expressions for branching logic, terminated by the end
keyword:
# Simulate flipping a coin
result = [:heads, :tails].sample
if result == :heads
puts 'The coin-toss came up "heads"'
else
puts 'The coin-toss came up "tails"'
end
In Ruby, if
statements are expressions that evaluate to a value, and the result can be assigned to a variable:
status = if age < 18
:minor
else
:adult
end
Ruby also offers C-style ternary operators (see here for details) that can be expressed as:
some_statement ? if_true : if_false
This means the above example using if-else can also be written as
status = age < 18 ? :minor : :adult
Additionally, Ruby offers the elsif
keyword which accepts an expression to enables additional branching logic:
label = if shirt_size == :s
'small'
elsif shirt_size == :m
'medium'
elsif shirt_size == :l
'large'
else
'unknown size'
end
If none of the conditions in an if
/elsif
chain are true, and there is no else
clause, then the expression evaluates to nil. This can be useful inside string interpolation, since nil.to_s
is the empty string:
"user#{'s' if @users.size != 1}"