DEV Community

loading...
Cover image for 49 Days of Ruby: Day 12 - Conditional Statements, Part I

49 Days of Ruby: Day 12 - Conditional Statements, Part I

bengreenberg profile image Ben Greenberg ・2 min read

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

In the past 11 days, we have learned about a wide variety of topics and gained a solid grounding in Ruby. Congrats!

Today, we are going to begin applying that learning in some real-world coding examples. The first building block that we will look at is conditional statements. Over the next two days, we will look at two varieties of them.

Let's start with the first conditional statement: the if/else.

If/Else Condition: What Is It?

The if/else pattern is an incredibly common coding choice because it reflects how we often think. Take the following scenario:

You are at the grocery store. You want to purchase apples. You think to yourself: if they have red apples, buy the red apples, else, purchase the green apples.

We have just described an if/else condition! If there are green apples, do X, else, do Y.

If/Else in Ruby

Now that we have a grasp of what it is. How do we build it in Ruby?

Here's an example:

morning_coffee = 'yes'

if morning_coffee == 'yes'
  puts 'Glad you enjoyed!'
else
  puts 'It is time to have your cup of coffee!'
end
Enter fullscreen mode Exit fullscreen mode

In the above example, we created a new variable called morning_coffee and set it to yes. We then created an if/else condition checking the value of morning_coffee. If morning_coffee equals yes we output one thing, else, we output something else.

What can you do with if/else conditions? Share your learning! Tomorrow, we'll dive into elsif, and how that can add more nuance to your conditional statement.

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

Discussion (0)

pic
Editor guide