CodeNewbie Community 🌱

Cover image for 49 Days of Ruby: Day 13 - Conditional Statements, Part II
Ben Greenberg
Ben Greenberg

Posted on • Originally published at on

49 Days of Ruby: Day 13 - Conditional Statements, Part II

Welcome to day 13 of the 49 Days of Ruby! 🎉

Yesterday, we dived into building conditional statements with if/else. This type of logic in our code allows us to make branches of possibilities. If there are green apples, buy them, else, buy the red apples.

Today, we're going to add another layer to the if/else that will give us the power to introduce even more flexibility to our conditional statements! I'm talking about the elsif.

What Is Elsif?

If we continue our example of buying apples in the grocery store, we can demonstrate the utility of the elsif:

If there are green apples, buy them, elsif there are red apples, buy them, else, go to the next store.

The introduction of the elsif brings the possibility of numerous branches to our conditional statements. Whereas, with only a single else you are limited to one other option, with the elsif you can build multiple ones.

Elsif in Ruby

How do we use this in Ruby?

Let's take a look at an example!

morning_coffee = 'yes'

if morning_coffee == 'no'
  puts 'Drink your coffee!'
elsif morning_coffee == 'not ready yet'
  puts 'Prepare your coffee!'
elsif morning_coffee == 'yes'
  puts 'Enjoy your day!'
  puts 'Do you even like coffee?'

Enter fullscreen mode Exit fullscreen mode

Did you notice in the above example that we used two separate elsif clauses? That's because you can use as many as you need. We end the condition with a final else that acts as a sort of catch-all in case morning_coffee is not equal to any of the possibilities in the elsif clauses.

Now that you know about the elsif what can you do with it? Tomorrow we continue the journey, and in the meantime, share your own learning with the community!

Come back tomorrow for the next installment of 49 Days of Ruby! You can join the conversation on Twitter with the hashtag #49daysofruby.

Top comments (0)