What Are Conditionals?

Learn about conditionals in Ruby.

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:

Press + to interact
number = 5
if 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"
else
puts "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:

  1. Running this code prints out The number is between 1 and 10 because the number assigned to the number variable in the first line is 5. For this number the method call number.between?(1, 10) returns true.

  2. Ruby executes the code in the if branch. The if branch is the block of code that comes after the line with the if keyword that’s indented, in this case by two spaces. Once it’s done executing the if branch, Ruby simply ignores the rest of the statement.

  3. If we change the number 5 in the first line to 15 and run the code again, it prints out The number is between 11 and 20. In this case, Ruby checks the first condition, number.between?(1, 10), which returns false.

  4. Therefore, Ruby ignores the if branch and checks the next condition on the elsif line, which is number.between?(11, 20). This method call returns true because 15 is between 11 and 20. Ruby executes the elsif branch and prints out this message. Again, once it’s done executing the elsif branch, Ruby ignores the rest of the statement.

  5. If we now change the number 15 to 25 and run the code again, then it prints out The number is bigger than 20. Again, Ruby checks the first condition and finds that it returns false. It then checks the second condition, which now also returns false. Ruby then executes the else 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 the end keyword.