Will
Will

Reputation: 5590

When are the () required in a method call in ruby/rails

In a helper I've got the code:

signed_in? ? link_to("Sign out", signout_path, :method => :delete) : link_to("Sign in", signin_path)

However the same thing can be written:

if(signed_in?)
  link_to 'Sign Out', signout_path, :method => :delete
else
  link_to 'Sign In', signin_path
end

In the second case, the parens for the method call aren't needed, in the first case they are. Why is that?

Upvotes: 1

Views: 88

Answers (2)

Adhitia Saputra
Adhitia Saputra

Reputation: 47

I think it just style of writing code..

i prefer option 1 , because it only using 1 line..

Upvotes: -1

Kyle d'Oliveira
Kyle d'Oliveira

Reputation: 6382

You don't need parens when there is no ambiguity in the function calls. For instance:

  foo 1, 2 resolves to foo(1,2)

and something like foo 1, bar 2 would be foo(1,bar(2)), but what about foo 1, bar 2, 3 that could go to either foo(1,bar(2,3)) or foo(1,bar(2),3)

So in the last example you would need to put in the parens yourself to tell ruby what you actually want it to do.

Also, if you ever want to call a method on the return value of the method you'll need parens too i.e foo(1,2).bar

Upvotes: 3

Related Questions