本文翻译自: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
本文详细解析了Ruby语言中&&和and运算符的区别,包括它们在布尔表达式和控制流中的应用,以及它们的优先级和绑定强度。文章通过实例展示了如何正确使用这些运算符,以避免常见的编程陷阱。
307

被折叠的 条评论
为什么被折叠?



