What Are Conditionals?
Learn about conditionals in Ruby.
We'll cover the following
What are conditionals?
Sometimes, we only want to perform an action if a certain criterion is met. Other times, we may want to check for a certain condition and then do one thing or another based on the answer. If this is true, then do that. Otherwise, do something else.
All practical programming languages have some way of expressing this, and in Ruby, it looks like this:
number = 5if number.between?(1, 10)puts "The number is between 1 and 10"elsif number.between?(11, 20)puts "The number is between 11 and 20"elseputs "The number is bigger than 20"end
It should be clear what this does and how it works.
Explanation
Let’s walk through it step by step:
-
Running this code prints out
The number is between 1 and 10
because the number assigned to thenumber
variable in the first line is5
. For this number the method callnumber.between?(1, 10)
returnstrue
. -
Ruby executes the code in the
if
branch. Theif
branch is the block of code that comes after the line with theif
keyword that’s indented, in this case by two spaces. Once it’s done executing theif
branch, Ruby simply ignores the rest of the statement. -
If we change the number
5
in the first line to15
and run the code again, it prints outThe number is between 11 and 20
. In this case, Ruby checks the first condition,number.between?(1, 10)
, which returnsfalse
. -
Therefore, Ruby ignores the
if
branch and checks the next condition on theelsif
line, which isnumber.between?(11, 20)
. This method call returnstrue
because15
is between11
and20
. Ruby executes theelsif
branch and prints out this message. Again, once it’s done executing theelsif
branch, Ruby ignores the rest of the statement. -
If we now change the number
15
to25
and run the code again, then it prints outThe number is bigger than 20
. Again, Ruby checks the first condition and finds that it returnsfalse
. It then checks the second condition, which now also returnsfalse
. Ruby then executes theelse
branch and prints out that message.
The elsif
and else
branches
The elsif
and else
branches are optional. We could have an if
statement without elsif
or else
branches, an if
statement with only an else
branch, or we could have an if
statement with just one or more elsif
branches. We could also combine all of them together as long as the following rules are adhered to for an if statement:
-
There must be an
if
branch. -
There can be many
elsif
branches. -
There can be one
else
branch, which must be the last branch to precede theend
keyword.