Dom*_*ger 335
警告:and
即使优先级低于=
您and
始终要避免的优先级
tad*_*man 236
实际差异是绑定力量,如果你没有做好准备,可能导致特殊的行为:
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
Run Code Online (Sandbox Code Playgroud)
同样适用于||
和or
.
And*_*imm 59
在Ruby的风格指南说,它比我更可以:
使用&&/|| 用于布尔表达式和/或用于控制流.(经验法则:如果必须使用外括号,则使用错误的运算符.)
# boolean expression
if some_condition && some_other_condition
do_something
end
# control flow
document.saved? or document.save!
Run Code Online (Sandbox Code Playgroud)
Gab*_*ley 37
||
并&&
使用您期望从编程语言中的布尔运算符的优先级绑定(&&
非常强大,||
稍微强一点).
and
并且or
优先级较低.
例如,不像||
, or
优先级低于=
:
> a = false || true
=> true
> a
=> true
> a = false or true
=> true
> a
=> false
Run Code Online (Sandbox Code Playgroud)
同样,与之相比&&
,and
优先级也低于=
:
> a = true && false
=> false
> a
=> false
> a = true and false
=> false
> a
=> true
Run Code Online (Sandbox Code Playgroud)
更重要的是,不像&&
和||
,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
Run Code Online (Sandbox Code Playgroud)
弱结合and
和or
可以是用于控制流目的是有用的:见http://devblog.avdi.org/2010/08/02/using-and-and-or-in-ruby/.
San*_*osh 18
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
Run Code Online (Sandbox Code Playgroud)
并且具有较低的优先级,大多数我们将其用作控制流修饰符,例如if
next if widget = widgets.pop
Run Code Online (Sandbox Code Playgroud)
变
widget = widgets.pop and next
Run Code Online (Sandbox Code Playgroud)
为或
raise "Not ready!" unless ready_to_rock?
Run Code Online (Sandbox Code Playgroud)
变
ready_to_rock? or raise "Not ready!"
Run Code Online (Sandbox Code Playgroud)
我更喜欢使用,如果但不和,因为如果是更容易理解,所以我只是忽视和和或.
参考