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.
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,
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
greeting.length is a 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 ...