你在 Ruby 里面放括号还是不放?

如果可能的话. . 你会在 Ruby 中留下括号吗?

29577 次浏览

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

Whichever is more readable usually.

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

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).

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.

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 tend to leave them out when doing assertions such as assert_equal. Maybe it's to make it domain specific language-like.

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.

If you've been programming for a long time, you'll probably have an "itch" to add parentheses, and in many cases there are good reasons for this.

The code is easier on the eyes though in my opinion, and I haven't run into a problem yet--if you're going to need parentheses, you'll know it beforehand before you have to run into the debugging script.