Ruby 中括号的惯用用法
array.include? 'foo' or array.include? 'bar'
是一个语法错误(意外的keyword_or)。括号解决了这个问题,但由于我是 Ruby 新手,我不知道以下哪一个被认为更惯用:
选项 1
array.include?('foo') or array.include?('bar')
选项 2
(array.include? 'foo') or (array.include? 'bar')
这是否取决于个人喜好,或者是否有一种方法被认为更“正确”?
array.include? 'foo' or array.include? 'bar'
is a syntax error (unexpected keyword_or). Parentheses solve the problem, but as I'm new to Ruby I've no idea which of the following is considered more idiomatic:
Option 1
array.include?('foo') or array.include?('bar')
Option 2
(array.include? 'foo') or (array.include? 'bar')
Does this come down to personal preference, or is one approach considered more "correct"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我建议您查看社区驱动的 Ruby 编码风格指南,这里特别是关于语法的部分。
对于属于内部 DSL 的方法(例如 Rake、Rails、RSpec)、Ruby 中具有“关键字”状态的方法(例如 attr_reader、puts)和属性访问方法,省略参数周围的括号。在所有其他方法调用的参数周围使用括号。 - 指南摘录
I'd suggest you take a look at the community-driven Ruby coding style guide, here particularly the section on Syntax.
Omit parentheses around parameters for methods that are part of an internal DSL (e.g. Rake, Rails, RSpec), methods that are with "keyword" status in Ruby (e.g. attr_reader, puts) and attribute access methods. Use parentheses around the arguments of all other method invocations. - excerpt from the guide
你确定这失败了吗?你最初的例子对我来说效果很好。
事实上,如果有什么东西可以被认为是惯用语的话,那就是这个了。
or
的低优先级允许在您省略括号时发挥作用。这个特性应该使其成为 Ruby 的惯用语(甚至是 Perl,其中或
是从 Perl 继承而来的)。选项 1 非常清楚,但考虑到您包含了括号,您确实不需要使用
或
。使用 || 可能更好,它与其他运算符一样具有很高的优先级,而且更常见。我认为为了看起来像英语而使用或
并不是一个很好的做法。它在语言中具有语义意义,并且可能最适合用于这些品质。当然,选项2是愚蠢的。如果您要包含括号,您也可以将它们用于方法签名。
希望这有帮助。
Are you sure that is failing? Your initial example works fine for me.
As a matter of fact, if anything could be considered idiomatic it would be that one. The low precedence of
or
allows this to work when you leave the parens off. This characteristic is something that should make it idiomatic to Ruby (and even Perl, whichor
is a hold over from).Option 1 is super clear, but considering you included the parens you really have no need to use
or
. It's probably better to use ||, which has a high precedence like other operators and is just more common. I think usingor
for the sake of it looking like english is not a great practice. It has a semantic meaning within the language and is probably best used for those qualities.Option 2 is silly of course. If you're going to include parens, you might as well use them for the method signature.
Hope this helps.
Avdi Grimm 认为你不应该 使用
and
或or
进行布尔逻辑。您应该仅使用and
或or
来控制流(类似于if
或unless
)根据他的建议,您应该使用
||
代替:Avdi Grimm reckons you shouldn't use
and
oror
for boolean logic. You should onlyand
oror
for control flow (analogous toif
orunless
)According to his recommendation, you should use
||
instead:选项 1 是首选,因为它对于其他语言也很常见。选项2看起来像LISP,现在不流行了。
Option 1 is preferred since it's common to other languages as well. Option 2 looks like LISP, which is not popular nowadays.