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
- Scala | Method Invocation
- Ruby Float to_r() method with example
- Ruby | String inspect Method
- Ruby | String hex Method
- Ruby | String include? Method
- Ruby | Integer > method
- Ruby | Date <=>() method
- Ruby | Date + method
- Ruby | Complex + method
- Ruby Float coerce() method with example
- Ruby | String delete_suffix! Method
- Ruby | String dump Method
- Ruby | String each_byte Method
- Ruby | Matrix == method
- Ruby | Matrix ** method
- Ruby | Rational * method
- Ruby | Set >= method
- Ruby Float to_d() - BigDecimal method with example
- Ruby | String * Method
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.