Ruby Language Truthy and Falsy values


Example

In Ruby, there are exactly two values which are considered "falsy", and will return false when tested as a condition for an if expression. They are:

  • nil
  • boolean false

All other values are considered "truthy", including:

  • 0 - numeric zero (Integer or otherwise)
  • "" - Empty strings
  • "\n" - Strings containing only whitespace
  • [] - Empty arrays
  • {} - Empty hashes

Take, for example, the following code:

def check_truthy(var_name, var)
  is_truthy = var ? "truthy" : "falsy"
  puts "#{var_name} is #{is_truthy}"
end

check_truthy("false", false)
check_truthy("nil", nil)
check_truthy("0", 0)
check_truthy("empty string", "")
check_truthy("\\n", "\n")
check_truthy("empty array", [])
check_truthy("empty hash", {})

Will output:

false is falsy
nil is falsy
0 is truthy
empty string is truthy
\n is truthy
empty array is truthy
empty hash is truthy