Method invocation refers to how a method is called in a program. The process of invoking a method in Ruby is quite easy since the use of parenthesis is optional. The use of parenthesis plays an important role when the invocation is embedded inside an expression consisting of other function calls or operators.
The Ruby interpreter makes use of the process known as method lookup or method resolution. In this method, when the Ruby interpreter has the method’s name and the object on which it is to be invoked, it searches for the method definition.
A Method Invocation Expression Comprises of 4 Components:
- The expression whose value is the object on which the method is call. Now, this expression is followed by either . or :: which is used to separate expression from the method name. This separator and expression is optional. If the separator and expression are absent, then method is invoked on the ‘self’.
- The name of the method being call.
- The parameter values is passed to the method. The list of comma-separated arguments can be passed to the method enclosed within parenthesis if the method contain more than one argument. These arguments are optional.
- An optional block of code enclosed in curly braces or by a ‘do/end’ pair. This code can be invoked this block of code with the help of the ‘yield’ keyword.
Example 1: In this example, we invoke a method with no arguments.
Example 2: In this example, we invoke a method with one argument.
Square Root of 36: 6.0
Example 3: In this example, we’re going to define a method with two arguments. Then we will call this method.
Example 4: In this example, we are going to invoke class methods.
Dog is barking Cat Elephant Dog is barking Cat Elephant