← Back to Ruby Course | Chapter 12: Ruby Best Practices | Lesson 4 of 6

Truthiness (only nil and false are falsy)

In Ruby, only nil and false count as no, and everything else counts as yes, even zero. It is like a door that opens for everyone except two special guests.
Syntax
ruby
if value
  # runs for anything except nil and false
end

Truthiness (only nil and false are falsy)

In Ruby, every value is truthy in a boolean context except nil and false -- notably, unlike many other languages, 0 and "" (empty string) are both truthy.

This is a frequent surprise for developers coming from languages where 0 or empty collections are falsy. Knowing this rule precisely avoids subtle conditional bugs.

Warning: Unlike many other languages, 0 and "" (empty string) are truthy in Ruby -- only nil and false are falsy.

Example: Truthiness (only nil and false are falsy)

markup
puts "0 is truthy" if 0
puts "empty string is truthy" if ""
puts "this won't print" if nil
puts "this won't print either" if false
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Expecting 0 to be false, as in C or JavaScript, when it is truthy in Ruby.
  2. Expecting an empty string or array to be falsy; use .empty?.
  3. Using if x to check for false and nil separately, when both are falsy and x.nil? tests only nil.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.