DEV Community

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

Posted on

5

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

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.

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

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