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:
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 10because the number assigned to thenumbervariable in the first line is5. For this number the method callnumber.between?(1, 10)returnstrue. -
Ruby executes the code in the
ifbranch. Theifbranch is the block of code that comes after the line with theifkeyword that’s indented, in this case by two spaces. Once it’s done executing theifbranch, Ruby simply ignores the rest of the statement. -
If we change the number
5in the first line to15and 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
ifbranch and checks the next condition on theelsifline, which isnumber.between?(11, 20). This method call returnstruebecause15is between11and20. Ruby executes theelsifbranch and prints out this message. Again, once it’s done executing theelsifbranch, Ruby ignores the rest of the statement. -
If we now change the number
15to25and 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 theelsebranch 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
ifbranch. -
There can be many
elsifbranches. -
There can be one
elsebranch, which must be the last branch to precede theendkeyword.