Ruby中&&和和操作符的区别是什么?


当前回答

Ruby风格指南说得比我还好:

使用&&/||作为布尔表达式,和/或控制流。(规则 拇指:如果你必须使用外括号,你就用错了 运营商)。

# boolean expression
if some_condition && some_other_condition
  do_something
end

# control flow
document.saved? or document.save!

其他回答

和&&相同,但优先级更低。它们都使用短路计算。

警告:and even的优先级比=低,所以你通常要避免使用and。何时使用和应该使用的例子可以在Rails指南“避免双重渲染错误”下找到。

我不知道这是Ruby的意图还是一个bug,但是试试下面的代码。这段代码在Ruby 2.5.1版本和Linux系统上运行。

puts 1 > -1 and 257 < 256
# => false

puts 1 > -1 && 257 < 256
# => true

实际的区别是结合强度,如果你没有准备好,这可能会导致奇怪的行为:

foo = :foo
bar = nil

a = foo and bar
# => nil
a
# => :foo

a = foo && bar
# => nil
a
# => nil

a = (foo and bar)
# => nil
a
# => nil

(a = foo) && bar
# => nil
a
# => :foo

||和or也是一样。

并且只检查第一个条件并给出结果 另一方面&&强检查两个条件并给出逻辑结果。

Ruby风格指南说得比我还好:

使用&&/||作为布尔表达式,和/或控制流。(规则 拇指:如果你必须使用外括号,你就用错了 运营商)。

# boolean expression
if some_condition && some_other_condition
  do_something
end

# control flow
document.saved? or document.save!