Truthy and Falsy values
suggest changeIn Ruby, there are exactly two values which are considered "falsy", and an if condition fails for them. 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", {})
This outputs:
false is falsy
nil is falsy
0 is truthy
empty string is truthy
\n is truthy
empty array is truthy
empty hash is truthy
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents