[英]Difference between "and" and && in Ruby?
Ruby中的&&
和and
运算符有什么区别?
实际的区别是结合强度,如果你没有准备好,它可能会导致特殊的行为:
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!
||
和&&
与您期望的编程语言中布尔运算符的优先级绑定( &&
非常强, ||
稍弱)。
and
和or
具有较低的优先级。
例如,不像||
, or
具有比=
低的优先级:
> a = false || true
=> true
> a
=> true
> a = false or true
=> true
> a
=> false
同样,与&&
不同, and
其优先级也低于=
:
> a = true && false
=> false
> a
=> false
> a = true and false
=> false
> a
=> true
更重要的是,不像&&
和||
, and
and or
以相同的优先级绑定:
> !puts(1) || !puts(2) && !puts(3)
1
=> true
> !puts(1) or !puts(2) and !puts(3)
1
3
=> true
> !puts(1) or (!puts(2) and !puts(3))
1
=> true
弱绑定and
和or
可能对控制流有用:参见http://devblog.avdi.org/2010/08/02/using-and-and-or-in-ruby/ 。
and
优先级低于&&
。
但是对于谦虚的用户,如果将其与其他优先级介于两者之间的运算符(例如赋值运算符)一起使用,则可能会出现问题:
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
and
具有较低的优先级,大多数情况下我们将它用作控制流修饰符,例如if
:
next if widget = widgets.pop
变成
widget = widgets.pop and next
对于or
:
raise "Not ready!" unless ready_to_rock?
变成
ready_to_rock? or raise "Not ready!"
我更喜欢使用if
而不是and
,因为if
更容易理解,所以我只是忽略and
和or
。
有关更多信息,请参阅“在 Ruby 中使用“and”和“or” ”。
我不知道这是 Ruby 的意图还是错误,但请尝试下面的代码。 此代码在 Ruby 版本 2.5.1 上运行,并在 Linux 系统上运行。
puts 1 > -1 and 257 < 256
# => false
puts 1 > -1 && 257 < 256
# => true
并且只检查第一个条件并给出结果,另一方面&&强烈检查两个条件并给出逻辑结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.