Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic use of parentheses in Ruby

Tags:

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"?

like image 275
davidchambers Avatar asked Oct 10 '11 01:10

davidchambers


People also ask

When to use parentheses in Ruby?

If a method has parameters, always use parentheses in the def of that method. If a method has one parameter, you may omit the parentheses in the method call. If a method has more than one parameter, always use parentheses in the method call. Always use parentheses if any of the arguments contain parentheses.

What do brackets mean in Ruby?

One thing that many early Rubyists fail to realize about square brackets ( [] ) in Ruby is that they are nothing more than a method with some added syntactic sugar. Everything is an object in Ruby, and square brackets are just a method call on those objects.

What is {} in Ruby?

The curly brackets { } are used to initialize hashes. The documentation for initializer case of { } is in ri Hash::[] The square brackets are also commonly used as a method in many core ruby classes, like Array, Hash, String, and others.

Are parentheses optional in Ruby?

That's right: In Ruby, when you define or call (execute, use) a method, you can omit the parentheses.


1 Answers

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) 
like image 89
Bozhidar Batsov Avatar answered Sep 30 '22 05:09

Bozhidar Batsov