Truthy 和 Falsy 的值
在 Ruby 中,有两个值被认为是假的,并且在作为 if 表达式的条件进行测试时将返回 false。他们是:
nil- boolean
false
所有其他值都被视为真实,包括:
0- 数字零(整数或其他)""- 空字符串\n- 仅包含空格的字符串[]- 空数组{}- 空哈希
例如,以下代码:
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", {})
将输出:
false is falsy
nil is falsy
0 is truthy
empty string is truthy
\n is truthy
empty array is truthy
empty hash is truthy