tags:

views:

642

answers:

8

When possible.. do you leave parentheses in or out in Ruby?

+2  A: 

I guess I do both, but I definitely keep them in if it adds to readability and avoids statements that look ambiguous.

Eli
+1  A: 

Whichever is more readable usually.

But I always use parentheses when I'm nesting function calls inside other ones' parameters

Gareth
+1  A: 

If you mean in function calls, I always put parenthesis because it's always easier to read. If you mean in conditions (if, while) I only put parenthesis when they're necessary.

mat
I agree. In php for example I can quickly spot a var by the $ prefix.. in javascript I can reconize a function by the parenthesis(). In Ruby the difference between a var or func (without parenthesis) is not always easy to see.
+1  A: 

I try to leave them out, if at all possible. I think it makes code easier to read (generally speaking).

mipadi
+3  A: 

I leave them out when I'm doing DSL-ish stuff, like t.column or has_many in rails. The rest of the time, it generally comes down to clarity, and it's probably an even split.

Matt Burke
+8  A: 

From the Elements of Ruby Style

Ruby allows you to leave out parenthesis, in general, resist this temptation.

Parenthesis make the code easier to follow. General Ruby style is to use them, except in the following cases:

  • Always leave out empty parentheses
  • The parentheses can be left out of a single command that is surrounded by ERb delimiters -- the ERb markers make sure the code is still readable
  • A line that is a single command and a single simple argument can be written without the parenthesis. Personally, I find that I do this less and less, but it's still perfectly readable. I tend not to like single lines in regular ruby code that have multiple arguments and no parentheses.
  • A lot of Ruby-based Domain Specific Languages (such as Rake) don't use parenthesis to preserve a more natural language feel to their statements.
Jason Navarrete
+1  A: 

I tend to leave them out when doing assertions such as assert_equal. Maybe it's to make it domain specific language-like.

Andrew Grimm
A: 

I use parens as comments to help the future me... who is likely to have fewer brain cells than the current me :-)

Nothing worse than looking at some code you wrote 2 years ago and misunderstanding it, so that you break something while modifying it.

If parens will save the future me a few minutes (or hours) in the future, I'll put in as many as needed to make the statement crystal clear.

-- John

John