Do you leave parentheses in or out in Ruby? [closed]

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


Solution 1:

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.

Solution 2:

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.

Solution 3:

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.