programmer321 programmer321 - 1 year ago 67
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"

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

if x
puts "XXX"
puts "YYY"

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download