Methods and Parentheses
Ruby allows parentheses to be omitted from most method invocations. In simple cases, this results in clean-looking code. In complex cases, however, it causes syntactic ambiguities and confusing corner cases. We’ll consider these in the sections that follow.
Optional Parentheses
Parentheses are omitted from method invocations in many common Ruby idioms. The following two lines of code, for example, are equivalent:
puts "Hello World"
puts("Hello World")
In the first line, puts looks
like a keyword, statement, or command built in to the language. The
equivalent second line demonstrates that it is simply the invocation
of a global method, with the parentheses omitted. Although the second
form is clearer, the first form is more concise, more commonly used,
and arguably more natural.
Next, consider this code:
greeting = "Hello" size = greeting.length
If you are accustomed to other object-oriented languages, you
may think that length is a
property, field, or variable of string objects. Ruby is strongly
object oriented, however, and its objects are fully encapsulated; the
only way to interact with them is by invoking their methods. In this
code, greeting.length is a method
invocation. The length method
expects no arguments and is invoked without parentheses. The following code is equivalent:
size = greeting.length()
Including the optional parentheses emphasizes that a method invocation is occurring. Omitting the parentheses in method invocations with no arguments gives ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access