在 Ruby 中,我们应该总是使用“&&”、“||”吗?用“或”代替“和”。除非特殊情况?
是不是大多数情况下,在Ruby中,最好使用&&
、||
而不是and
、或
,除非是一些特殊情况。
我认为 Ruby 的设计原则之一就是尽可能减少意外,因此使用 and
或 or
实际上会带来一些惊喜...例如 and 的优先级不高于
或
,而 &&
的优先级高于 ||
。
所以我认为大多数情况下,使用&&
、||
。我知道在某些特殊情况下,可能需要使用 and
、or
,但我认为如果将它们与 &&
、< code>||,当您不久前开始使用 Ruby 的同事需要编辑您的代码时,迟早可能会产生错误。
Is it true that in most cases, in Ruby, it is best to use &&
, ||
instead of and
, or
, unless it is some special situations.
I think one of Ruby's design principles is to have least surprises as possible, so using and
, or or
actually have some surprises... such as and
not having a higher precedence than or
, while &&
has a higher precedence than ||
.
So I think in most cases, use &&
, ||
. In know in some special situations, it may require using and
, or
, but I think if those are intermixed with &&
, ||
, sooner or later it may create bugs when your coworkers who started in Ruby not so long ago need to edit your code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的。依靠
and
和or
进行布尔逻辑是将微妙的错误引入应用程序的好方法。不过,他们确实有一席之地。当用作控制流运算符时,它们是一个安全且可读的选项。
我基本上和你的感觉一样,直到我读到 这篇优秀的博客文章。
Yes. Relying on
and
andor
for boolean logic is a good way to introduce subtle bugs into your application.They do have a place, though. They are a safe and readable option when used as control flow operators.
I basically felt the way you did until I read this excellent blog post.
《Ruby 编程语言》一书(David Flanagan 和 Yukihiro Matsumoto)给出了使用“and”的两个原因。
可读性:
如果 x > 0 且 y > 0 且未定义?然后
d = Math.sqrt(x*x +y*y)
end
充分利用较低的优先级:
if a = get_from_db(x) and b = get_from_db(y) then do_stuff_with_true_values(a, b) end
(由我改编的代码)最后一个不适用于“&&”。
就我个人而言,为了便于阅读,我将“and”和“or”与括号结合使用,以防有疑问。-
The book 'The Ruby Programming Language' (David Flanagan & Yukihiro Matsumoto) gives two reasons to use 'and'.
readability:
if x > 0 and y > 0 and not defined? d then
d = Math.sqrt(x*x +y*y)
end
make good use of the lower precedence:
if a = get_from_db(x) and b = get_from_db(y) then do_stuff_with_true_values(a, b) end
(code adapted by me) The last one just wouldn't work with '&&'.
Personally, I use 'and' and 'or' combined with parentheses in case of doubt, for readability.-
这是因为
and
、or
¬
的优先级低于&&
、||
和!
。为什么?因为它源于 Perl。 Larry Wall 作为一名语言学家,希望以下内容能够发挥作用:
如果您替换
或 与
||
那么该语句将被解析如下:这不好!
所以对于像 Perl 和 Perl 这样的语言来说, Ruby 中括号通常是可选的,那么这就是解决方案。否则,您需要编写:
请参阅perlop“逻辑非、与、或、定义或、和独占或 & Perl 和 Ruby 中的逻辑运算符 用于全面调整
/I3az/。
It's because
and
,or
¬
have lower precedence than&&
,||
and!
.Why? Because it stems from Perl. Larry Wall being a linguist wanted the following to work:
If you replace the
or
with||
then that statement would be parsed like this:Which is not good!
So for languages like Perl & Ruby where parenthesis are often optional then this was the solution. Otherwise you would need to write:
See perlop "Logical Not, And, or, Defined or, and Exclusive Or && Logical operators in Perl and Ruby for the full shake down.
/I3az/