Jeff Burghess
Jeff Burghess

Reputation: 383

Why do we omit parenthesis only some of the time?

for example,

validates :name, presence: true 

instead of

validates(:name, presence: true)

but we keep parentheses in

@user = User.find(params[:id])

Taken from the hartl book.

Upvotes: 0

Views: 178

Answers (3)

Petr Gazarov
Petr Gazarov

Reputation: 3811

Parenthesis vs no parenthesis in most cases is a matter of convention. It's perfectly fine to leave off parenthesis.

Usually when using DSL in Ruby (e.g. validates), you would omit parenthesis. When calling regular instance or class methods, most often than not, I've seen people include them.

In more complicated examples, you would want to include parenthesis for clarity, and to make sure you are in control of how it is executed.

Upvotes: 0

Amadan
Amadan

Reputation: 198324

validates, attr_reader, Sinatra's get, RSpec's describe and similar function calls can be seen as declarations. In this case it is typical to leave parentheses off. "Real" function calls are usually written with parentheses for clarity.

In the words of one of more popular Ruby Style Guides:

  • Omit parentheses around parameters for methods that are part of an internal DSL (e.g. Rake, Rails, RSpec), methods that have "keyword" status in Ruby (e.g. attr_reader, puts) and attribute access methods. Use parentheses around the arguments of all other method invocations

[...]

  • Omit both the outer braces and parentheses for methods that are part of an internal DSL.

Upvotes: 2

DerektheDev
DerektheDev

Reputation: 103

It's a Ruby stylistic choice; you can do either. Most people, including myself, omit parentheses most of the time. Ruby as a language tries very hard to stay out of your way and give you several ways of achieving the same thing, whichever feels right at a given moment.

You could optionally use them for clarity, or most often for long lines of code where the interpreter may stumble over what's an argument versus the next statement, etc.

Your last example would work fine without the parens.

Upvotes: 1

Related Questions