Chapter 11: Conditions
We’ve seen the comparison operators like <, >, <=, >=, ==, ===, !, !=, etc. These operators are typically used in control statements, like conditionals, loops, etc. Conditionals are the first control structure we’ll see.
Conditions are a part of control flow. Whenever we make a decision, we’re using a conditional. If this, then that. You get the idea.
We can decide to do something, or something else, based on a conditional. For example,
age = 15
if (age > 15)
print 'you can drive'
end
The code within the if..end block executes only when the condition provided to the if statement evaluates to true.
If you want to do something else when the condition is false, use the else statement with if.
age = 15
if (age > 15)
print 'you can drive a car'
else
print 'you can ride a bicycle'
end
If you have more than one conditions, chain them using elsif as follows:
age = 15
if (age > 15)
print 'you can drive a car'
elsif (age > 5)
print 'you can ride a bicycle'
else
print 'you can ride a tricycle'
end
When you have too many conditionals, it’s better to use a case..when statement.
age = 18
case age
when 0..5
print 'tricycle'
when 6..15
print 'bicycle'
else
print 'car'
end
You might be wondering what’s the 0..5 syntax. It’s called a Range. It indicates the range from the number 0 to the number 5, including both. We’ll learn about it in a following chapter.
To fully understand the power of Ruby’s case statement, check out the following article: Ruby’s Switch Statement is More Flexible Than You Thought