0
0
Rubyprogramming~5 mins

Truthy and falsy values (only nil and false are falsy) in Ruby

Choose your learning style9 modes available
Introduction

In Ruby, understanding which values count as true or false helps you control decisions in your code easily.

When you want to check if a variable has a meaningful value before doing something.
When you write conditions to run code only if something is true.
When you want to avoid errors by making sure a value is not nil or false before using it.
When you want to simplify your code by relying on Ruby's true/false rules.
When you debug why some code runs or skips based on values.
Syntax
Ruby
if value
  # runs if value is truthy
else
  # runs if value is falsy (nil or false)
end

Only nil and false are treated as false in Ruby.

Everything else, including 0, empty strings, and empty arrays, is truthy.

Examples
Since nil is falsy, the else branch runs.
Ruby
if nil
  puts "This won't print"
else
  puts "nil is falsy"
end
false is falsy, so else branch runs.
Ruby
if false
  puts "This won't print"
else
  puts "false is falsy"
end
Unlike some languages, 0 is truthy in Ruby, so this prints.
Ruby
if 0
  puts "0 is truthy"
end
Empty strings are also truthy in Ruby.
Ruby
if ""
  puts "Empty string is truthy"
end
Sample Program

This program checks different values and prints if they are truthy or falsy in Ruby.

Ruby
values = [nil, false, 0, "", [], true]

values.each do |val|
  if val
    puts "#{val.inspect} is truthy"
  else
    puts "#{val.inspect} is falsy"
  end
end
OutputSuccess
Important Notes

Remember, only nil and false count as false in Ruby.

This makes Ruby conditions simple and predictable.

Summary

Only nil and false are falsy in Ruby.

Everything else, even 0 or empty strings, is truthy.

Use this to write clear and simple condition checks.