Guide to Using Multiple If-Else Conditionals in Ruby
In this lesson, we are going to learn more about multiple if-else conditionals in the same program. Ruby has a little bit different syntax on this one, so I thought it would be nice to walk through it slowly.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In this lesson we are going to extend our knowledge of conditionals by learning about the if-elsif mechanism. This tool allows us to setup multiple conditional scenarios for our programs to manage data flow. Ruby has a slightly odd syntax on this functionality, so let's walk through it one step at a time.

if/elsif Conditional Code Example

To review I'm going to start off with a regular if statement.

x = 10
y = 100
z = 10

if x == y
  puts "x is equal to y"
end

If you run this program nothing will print out since x is not equal to y. This is what you already know. Now, I'm going to add some additional scenarios.

if x == y
  puts "x is equal to y"
elsif x > z
  puts "x is greater than z"
else
  puts "Something else"
end

Essentially, this code is going to check if x is equal to y, and it's not it moves down to the next condition and checks if x is greater than z, which is not true again. So, it finally prints Something else. Whenever you have an else statement in a program like this it's treated like a fallback value, which means that it will catch be processed if none of the conditionals above it were true.

Now, if I make a small change and alter the elsif statement to read: x is greater than or equal to z, then my output should be x is greater than or equal to z.

if x == y
  puts "x is equal to y"
elsif x >= z
  puts "x is greater than or equal to z"
else
  puts "Something else"
end

The Conditional Workflow

In these multiple if-else conditionals Ruby moves in a sequential order from one condition to the other. When any particular condition is satisfied it:

  • Enters that code block
  • Performs the logic
  • Exits out of the if-else loop

Now, what happens when more than one condition is true?

if x == y
  puts "x is equal to y"
elsif x >= z
  puts "x is greater than or equal to z"
elsif x < z
  puts "x is less than y"
else
  puts "Something else"
end

In the above example, both the elsif statements are true. Still, Ruby will only process the elsif x >= z because it is true. From there it will simply exit the if-else workflow. So, the output is the same.

This is something that you should keep in mind while creating an if-else statement in Ruby. I've had confusing bugs arise in programs where I couldn't figure out why a program wasn't generating the value I expected. And I ended up discovering that a conditional higher up the conditional chain was resolving to a true value and the condition I wanted the program to reach was skipped completely.