开发者

Idiomatic use of parentheses in Ruby

开发者 https://www.devze.com 2023-04-11 16:24 出处:网络
array.include? \'foo\' or array.include? \'bar\' is a syntax error (unexpect开发者_如何学Goed keyword_or). Parentheses solve the problem, but as I\'m new to Ruby I\'ve no idea which of the following
array.include? 'foo' or array.include? 'bar'

is a syntax error (unexpect开发者_如何学Goed 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"?


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

class Person
  attr_reader :name, :age

  # omitted
end

temperance = Person.new('Temperance', 30)
temperance.name

puts temperance.age

x = Math.sin(y)
array.delete(e)


Are you sure that is failing? Your initial example works fine for me.

ruby-1.9.2-p290 :002 > array = ['bar']
 => ["bar"] 
ruby-1.9.2-p290 :003 > array.include? 'foo' or array.include? 'bar'
 => true

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, which or 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 using or 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 reckons you shouldn't use and or or for boolean logic. You should only and or or for control flow (analogous to if or unless)

According to his recommendation, you should use || instead:

array.include?('foo') || array.include?('bar')


Option 1 is preferred since it's common to other languages as well. Option 2 looks like LISP, which is not popular nowadays.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号