Ruby中“ and”和&&之間的區別?

本文翻譯自: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. andor具有較低的優先級。

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: andor綁定具有相同的優先級:

> !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/ . 弱綁定andor可能對控制流有用:請參閱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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章