#---Boolean---
true and false are the two boolean objects that Ruby gives us to make decisions.
true is the only object of the class TrueClass,
and false is the only object of the class
FalseClass.
p true.class # => TrueClass
p false.class # => FalseClass
The conditions you give in the conditionals must
evaluate to true or false.
But they can also evaluate to a truthy or falsy
value as well.
What?
Yes. Truthy things are things that are considered true in the Eye Of The God. Falsy things⦠are not.
There are only two falsy things in Ruby:
Everything else is truthy. Everything else.
This means, besides regular ruby objects, all of these are truthy as well:
''[]{}00.0You might be used to seeing some of these as falsy in other languages, like JavaScript or Python.
So be careful:
str = ''
if str
p "There's something"
else
p "There's nothing"
end
## => "There's something"
Here, you probably expected the else part to run. But that’s not what happened.
The right way to check for empty string is:
if str.empty? # or str.size == 0
p "There's nothing"
else
p "There's something"
end
## => "There's nothing"
You can get the boolean context of any ruby object
with the “bang” boolean negation operator !:
!) to get its
opposite boolean value. (Also called the not
operator.)p !'some string' # => false
p !"" # => false
p ![] # => false
p ![11, 22, 33] # => false
p !nil # => true
!!) to get its
actual boolean value. (Also called the not not
operator.)p !!'some string' # => true
p !!"" # => true
p !![] # => true
p !![11, 22, 33] # => true
p !!nil # => false
These are useful when you define interrogative methods:
def no_posts?
!has_posts?
end
Note that you don’t have to use the not not operator in the conditionals every time to check the object’s truthiness. You can use the object as-is. Ruby will still infer it correctly. (But be careful of the caveat above.)
h = {a: 'aa', b: 'bb'}
p 'h is truthy' if h
## => "h is truthy"
## (What happens if h is an empty hash?)
#