Idiomatic use of parentheses in Ruby

davidchambers picture davidchambers · Oct 10, 2011 · Viewed 16.3k times · Source
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"?

Answer

Bozhidar Batsov picture Bozhidar Batsov · Oct 10, 2011

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)