What is a boolean?
A boolean is a value used in a logic statement to say if something is considered true or false.
This can be used to make decisions.
In Ruby we don’t have a Boolean class, but we have boolean objects!
Which are the singleton objects of
You get a boolean value when you use methods like:
And compare things with an equal sign:
1 == 1 # true
Keep in mind that
== in Ruby is also a method, this means that the behavior can change depending on how this method is implemented.
What is a truthy value?
It’s a value that’s considered
true in a boolean context, like an if statement.
Everything in Ruby is truthy but these two:
These two values, and ONLY these two, we call “falsy”.
This means that if you have a condition…
if bacon puts "we got bacon" end
Ruby checks if
bacon is truthy (anything but
nil) before printing the string.
In other words:
You don’t have to check for nil if you aren’t calling a method on
Sometimes you want to call a method on the object.
if bacon.stock > 10 end
This will give you an error if
bacon is nil, to avoid this you can do the following…
if bacon&.stock > 10 end
&. is called the safe navigation operator & it was introduced in Ruby 2.3.
Have you seen these methods ending in a question mark?
We call these “predicate methods” & by convention they always return either
You can write your own:
def published? # ... end def ready? # ... end
This is a great pattern that will make your code feel more like Ruby.
We just covered boolean methods, which are great, but you want to avoid is boolean parameters.
def bacon(raw) end bacon(false)
When you look at
bacon(false) you have no idea what this
You would have to dig into the code to find out.
On top of that, a boolean value means that your method is going to be more complex than it needs to be.
Split the method in two, or design your code in a way where this isn’t necessary.
TrueClass & FalseClass implement a few methods.
Like to_s, and inspect.
But more interesting are:
What are these strange-looking methods?
Here’s a boolean logic table:
|Name||Symbol||TRUE / TRUE||TRUE / FALSE|
true & true
While we often don’t use boolean logic in our code it forms the foundation of how computers work, so it’s interesting to know about it.
You have learned about boolean values in Ruby! Remember that everything is “truthy”, with the only exceptions being
Don’t forget to share this article so more people can find it 🙂
Thanks for reading.