Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

What do brackets mean in Ruby?

Square brackets [] are used as class methods in lots of Ruby classes, including String, BigNum, Dir and confusingly enough, Hash. So: Hash["key" => "value"] is just as valid as: { "key" => "value" } Follow this answer to receive notifications.

What do square brackets mean in Ruby?

Square brackets indicate character classes in Ruby regular expressions.

Does method order matter in Ruby?

You could define method in any order, the order doesn't matter anything.

What happens when you call a method in Ruby?

A method in Ruby is a set of expressions that returns a value. With methods, one can organize their code into subroutines that can be easily invoked from other areas of their program. Other languages sometimes refer to this as a function.


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.

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.


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.


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


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.


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