CodeNewbie Community 🌱

Cover image for 49 Days of Ruby: Day 7 - Booleans
Ben Greenberg
Ben Greenberg

Posted on • Originally published at on

49 Days of Ruby: Day 7 - Booleans

Welcome to day 7 of the 49 Days of Ruby! πŸŽ‰

Today we are going to discuss another important data type to know about as we begin our journey in Ruby. Today is all about the important Boolean.

What does Boolean mean?

The name Boolean comes from the English mathematician, George Boole. His seminal work The Laws of Thought gave rise to Boolean algebra. We won't get into too much math 😌, but basically, Boolean algebra is algebra where the values are either true or false.

As you can probably gather at this point if Boolean algebra is where the values are either true or false then a Boolean is a data type equalling either true or false.

Like many programming languages, Ruby offers you the ability to leverage Booleans in your code. Here is a quick example:

monday = true

if monday == true
  puts "Today is the first day of the workweek, enjoy!"

Enter fullscreen mode Exit fullscreen mode

In the example above we set the variable monday to equal true and then make a conditional statement based on that value. If monday is true then we output a string, and if not, we do nothing.

That example is a relatively straightforward use case, but it lays the groundwork for what kind of things you can do with Booleans.

πŸŽ“ Extra credit: What Class do Booleans belong to? You haven't learned about Classes yet. They are a way of organizing types of things together. For example, you might have a CatClass for all types of cats. In many programming languages, there is a standard Boolean type Class for Booleans. Not in Ruby!

To find out the Ruby Classes for Booleans go ahead and open up a session of IRB in your terminal:

irb> true.class
=> TrueClass
irb> false.class
=> FalseClass

Enter fullscreen mode Exit fullscreen mode

That's right! There is not one class for Booleans, but two! The true value belongs to TrueClass and the false value belongs to FalseClass.

There are several implications for that. One of them, is you cannot just check if a thing is a Boolean, because it could be either TrueClass or FalseClass. We'll cover that more later when we get to Classes. πŸŽ“

Besides true and false, what other things fall into the category of truthy or falsy?

When it comes to false values, there is only false itself or nil.

There are more things that are truthy though, here are some of them:

  • 0
  • '' (empty string)
  • [] (empty array)

You can find more in this GitHub Gist.

How will you use Booleans in your Ruby journey? Continue experimenting in IRB and share what you learned in a blog post or on Twitter!

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)