Ruby真实和虚假的价值观
示例
在Ruby中,恰好有两个值被视为“虚假”,并且在作为if表达式的条件进行测试时将返回false。他们是:
nil
布尔值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
热门推荐
7 带清的简短祝福语
10 近代生日祝福语简短精辟
11 关于开车的祝福语简短
12 参加婚礼祝福语大全简短
13 股市祝福语简短10字
14 妈妈祝福语简短16字
15 祖国生日祝福语简短英文
16 中考祝福语简短卡片大全
17 生女儿的祝福语简短
18 祝贺开业文案祝福语简短