Ruby 为什么'z | | y==0'没有返回我期望的结果?
因此,我正在学习Codecademy中的Ruby课程,并编写以下代码Ruby 为什么'z | | y==0'没有返回我期望的结果?,ruby,variables,if-statement,Ruby,Variables,If Statement,因此,我正在学习Codecademy中的Ruby课程,并编写以下代码 z = 39 y = 39 if z && y != 39 print "God if it prints this, this code will be a failure!" elsif z || y == 0 print "dont print this code" else print "Success!" end 出于某种原因,它运行elsif并说,“不要打印此代码”有人能
z = 39
y = 39
if z && y != 39
print "God if it prints this, this code will be a failure!"
elsif z || y == 0
print "dont print this code"
else
print "Success!"
end
出于某种原因,它运行elsif并说,“不要打印此代码”有人能给我解释一下吗?因为作为对象的
z
不会像您的z=39
那样被视为false
,也不会被设置为boolean
文本值false
或nil
对于Ruby,任何非
nil
或任何设置为boolean
文本值false
的对象都将在返回boolean
类型值的表达式中返回true
。因为作为对象的z
不会被视为false
,因为z=39
,未设置为boolean
literal值false
或nil
对于Ruby,任何非
nil
或任何设置为boolean
literal valuefalse
的对象都将在返回boolean
类型值的表达式中返回true
。这里需要了解两件事:如何工作和Ruby如何将对象转换为true/false
工作原理:
你写道:
if z && y != 39
您希望Ruby这样解释:
if (z != 39) && (y != 39)
if (z) && (y != 39)
但实际上Ruby是这样解释的:
if (z != 39) && (y != 39)
if (z) && (y != 39)
将对象转换为真/假
任何不是nil或false的Ruby对象都将计算为true。因此,在您的情况下,我们有:
if z && y != 39
即:
if true && false # z is not nil, so true, and y == 39 so the second part is false
if true || false # z is still not nil, y != 0 so the second part is false
这当然是错误的
然后
即:
if true && false # z is not nil, so true, and y == 39 so the second part is false
if true || false # z is still not nil, y != 0 so the second part is false
true | | false求值为true,因此“不打印此代码”将被输出。这里您需要了解两件事:如何&工作以及Ruby如何将对象转换为true/false 工作原理: 你写道:
if z && y != 39
您希望Ruby这样解释:
if (z != 39) && (y != 39)
if (z) && (y != 39)
但实际上Ruby是这样解释的:
if (z != 39) && (y != 39)
if (z) && (y != 39)
将对象转换为真/假
任何不是nil或false的Ruby对象都将计算为true。因此,在您的情况下,我们有:
if z && y != 39
即:
if true && false # z is not nil, so true, and y == 39 so the second part is false
if true || false # z is still not nil, y != 0 so the second part is false
这当然是错误的
然后
即:
if true && false # z is not nil, so true, and y == 39 so the second part is false
if true || false # z is still not nil, y != 0 so the second part is false
true | | false求值为true,因此“不打印此代码”被输出。我认为你是唯一真正理解OP试图实现的+1我认为你是唯一真正理解OP试图实现的+1