本文翻譯自:Difference between “and” and && in Ruby?
Ruby中的&&
和and
運算符有什麼區別?
#1樓
參考:https://stackoom.com/question/5zBK/Ruby中-and-和-amp-amp-之間的區別
#2樓
The Ruby Style Guide says it better than I could: Ruby樣式指南說得比我更好:
Use &&/|| 使用&& / || for boolean expressions, and/or for control flow. 用於布爾表達式和/或用於控制流。 (Rule of thumb: If you have to use outer parentheses, you are using the wrong operators.) (經驗法則:如果必須使用外部括號,則說明使用了錯誤的運算符。)
# boolean expression
if some_condition && some_other_condition
do_something
end
# control flow
document.saved? or document.save!
#3樓
||
and &&
bind with the precedence that you expect from boolean operators in programming languages ( &&
is very strong, ||
is slightly less strong). 和&&
與編程語言中布爾運算符所期望的優先級綁定( &&
非常強大, ||
稍弱一些)。
and
and or
have lower precedence. and
和or
具有較低的優先級。
For example, unlike ||
例如,與||
不同 , or
has lower precedence than =
: , or
優先級低於=
:
> a = false || true
=> true
> a
=> true
> a = false or true
=> true
> a
=> false
Likewise, unlike &&
, and
also has lower precedence than =
: 同樣,與&&
不同, and
優先級比=
低:
> a = true && false
=> false
> a
=> false
> a = true and false
=> false
> a
=> true
What's more, unlike &&
and ||
而且,與&&
和||
不同 , and
and or
bind with equal precedence: , 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
The weakly-binding and
and or
may be useful for control-flow purposes: see http://devblog.avdi.org/2010/08/02/using-and-and-or-in-ruby/ . 弱綁定and
和or
可能對控制流有用:請參閱http://devblog.avdi.org/2010/08/02/using-and-and-or-in-ruby/ 。
#4樓
and
is the same as &&
but with lower precedence . and
與&&
相同,但優先級較低 。 They both use short-circuit evaluation . 他們都使用短路評估 。
WARNING: and
even has lower precedence than =
so you'll usually want to avoid and
. 警告: and
甚至有優先級低於=
所以你通常會想避免and
。 An example when and
should be used can be found in the Rails Guide under " Avoiding Double Render Errors ". 在Rails指南的“ 避免雙重渲染錯誤 ”下可以找到何時and
應使用的示例。
#5樓
The practical difference is binding strength, which can lead to peculiar behavior if you're not prepared for it: 實際的區別是綁定強度,如果您不準備這樣做,它可能會導致特殊的行爲:
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
The same thing works for ||
相同的東西適用於||
and or
. 和or
。
#6樓
and
has lower precedence than &&
. and
具有比&&
更低的優先級。
But for an unassuming user, problems might occur if it is used along with other operators whose precedence are in between, for example, the assignment operator: 但是對於謙虛的用戶而言,如果將其與優先級介於兩者之間的其他運算符一起使用,則可能會出現問題,例如:
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