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


当前回答

并且具有较低的优先级,通常我们将其用作控制流修饰符,例如:

next if widget = widgets.pop

就变成了

widget = widgets.pop and next

或:

raise "Not ready!" unless ready_to_rock?

就变成了

ready_to_rock? or raise "Not ready!"

我更喜欢用if而不是and,因为if更容易理解,所以我忽略and和or。

更多信息请参考“Using”和“and”或“in Ruby”。

其他回答

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

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的意图还是一个bug,但是试试下面的代码。这段代码在Ruby 2.5.1版本和Linux系统上运行。

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

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

并且优先级低于&&。

但对于一个不太谦虚的用户来说,如果它与其他优先级介于两者之间的操作符一起使用,例如赋值操作符,则可能会出现问题:

def happy?() true; end
def know_it?() true; end

todo = happy? && know_it? ? "Clap your hands" : "Do Nothing"

todo
# => "Clap your hands"

todo = happy? and know_it? ? "Clap your hands" : "Do Nothing"

todo
# => true

并且具有较低的优先级,通常我们将其用作控制流修饰符,例如:

next if widget = widgets.pop

就变成了

widget = widgets.pop and next

或:

raise "Not ready!" unless ready_to_rock?

就变成了

ready_to_rock? or raise "Not ready!"

我更喜欢用if而不是and,因为if更容易理解,所以我忽略and和or。

更多信息请参考“Using”和“and”或“in Ruby”。

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

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