Truthy and falsey in Ruby

Every object in Ruby has a boolean value which means that all objects are considered either true or false in a boolean context. Objects that are considered true in a boolean context are truthy and objects that are considered false in a boolean context are falsey. false and nil are the only falsey objects and every other object is truthy. In some programming languages, 0 is falsey, but 0 is truthy in Ruby.

puts statements can be used to demonstrate the boolean values of objects:

>> puts "hi" if 5
>> puts "hi" if 0
>> puts "hi" if nil
>> puts "hi" if false

All puts statements return nil, so I removed the return values to focus on the puts output. The “hi” String is printed with 0 and 5 because these are truthy objects, but not printed for nil and false because these are falsey objects.

Beginner Ruby programmers tend to avoid making boolean comparisons unless the object is true or false, but boolean comparisons based on the truthyness/falseyness of an object are quite useful and should be used frequently.


One thought on “Truthy and falsey in Ruby

  1. Pingback: RSpec: be true & be_true Are Different! | Ben Gribaudo

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s