liveBook · Manning

Parenthesis

As explained in The Well-Grounded Rubyist, Fourth Edition

Parentheses are Ruby syntax used to delimit the arguments of a method call and resolve syntactic ambiguity.

Parentheses delimit method arguments in Ruby. They are often optional, but adding them can remove ambiguity and make a method call easier to read. section 1.1.4

Making the argument boundary explicit

Both "100".to_i and "100".to_i(9) call to_i, but the second form visibly supplies 9 as an argument and converts the string as a base-9 number, producing 81. section 1.1.4

Parentheses also help Ruby distinguish method calls from nearby syntax:

  • An identifier followed by parentheses is parsed as a method call, including an empty call such as x(). Without parentheses, an unresolved identifier may be reported as either an undefined local variable or method. section 2.5.4
  • A hash used as the first argument must be enclosed in curly braces and placed inside parentheses; otherwise Ruby can interpret the braces as a code block. section 9.3.7
  • A final hash argument may omit its curly braces, but parentheses around the complete argument list clarify where the arguments begin and end. section 9.3.7
x = "100".to_i

Compare a method call without an explicit argument list to the same call with parentheses and an argument. section 1.1.4

my_method({ NY: "New York" }, 100, "another argument")

Use parentheses to force a leading hash to remain a method argument rather than a code block. section 9.3.7

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains optional delimiters, identifier parsing, and hash edge cases without developing Ruby's complete parsing rules.
Examples
Uses to_i base conversion, x(), unresolved x, and hash arguments with and without enclosing parentheses.
What it assumes
Assumes basic Ruby methods and arguments while establishing how Ruby distinguishes keywords, local variables, and method calls.
What you can do after
Apply parentheses to clarify Ruby method calls and prevent argument syntax from being mistaken for variables or blocks.
How it connects
Connects method calls, arguments, local variables, hashes, code blocks, and keyword arguments.

Also explained in

Compare how 2 books explain parenthesis →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.