Ruby Language Control Flow Truthy and Falsy values

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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


Got any Ruby Language Question?