使用带有赋值的`和`

Ten*_*eej 1 ruby operator-precedence logical-operators

我希望以下评估(a < b)以及(b < c)返回no.

a = 1
b = 4
c = 3
@test = (a < b) and (b < c)
if @test
  puts "yes"
else
  puts "no"
end
Run Code Online (Sandbox Code Playgroud)

我没有得到我期望的行为.它返回yes并且似乎仅评估(a < b)而不是(b < c).我认为问题在于and.

pot*_*hin 5

你正在使用and而不是&&,所以实际上,你设置@test的结果是(a<b),而不是(a<b) and (b<c)(=优先级高于and,而&&优先级高于=).

  • @Tennesseej:那你做错了.你需要的是`@test =(a <b)&&(b <c)`或`@test =((a <b)和(b <c))`或`@test =((a <b) &&(b <c))`.您的原始代码相当于`(@test =(a <b))和(b <c)`. (2认同)