DEV Community

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

Posted on

4 2

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!'
else
  puts 'Do you even like coffee?'
end
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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay