programmer321 programmer321 - 29 days ago 6
Ruby Question

With Ruby Booleans, what are you checking for if there are no equality statements?

I am using a tutorial, and it has a conditional like this:

if Restaurant.method1
puts "XXX"
elsif Restaurant.method2
puts "YYY"
end


Both methods return a Boolean value of
true
or
false
. Similarly, for variables, I have seen something similar:

if x
puts "XXX"
else
puts "YYY"
end


I am wondering what exactly are you checking for considering that there is no equality operator (
==
) or assignment operator (
=
)? There must be some sort of equality check that perhaps hidden by the simplistic nature of Ruby, because I'm thinking this logically in my head and "If x", and "If Restaurant.method" both don't really make any sense as a conditional without some sort of check.

Answer

This is a common paradigm in programming, not a Ruby abstraction. You are checking if something is truthy. In ruby in particular, everything is truthy except false and nil. Try it yourself in your console if you want to test this:

!!1 # => true
!!0 # => true
!![] # => true
!!{} # => true

...etc, whereas

!!false # => false
!!nil # => false

Important note: this is only the case for Ruby. Other languages have different rules. For example, in some languages 0 is falsy. It's important to learn these early on when learning a new language.