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_str = 'GeeksforGeeks'
puts example_str.length
|
Output:
13
Example 2: In this example, we invoke a method with one argument.
number = Math.sqrt( 36 )
puts "Square Root of 36:"
puts number
|
Output:
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.
def add(a, b)
a + b
end
c = add( 20 , 30 )
d = add( 45 , 90 )
puts c
puts d
|
Output:
50
135
Example 4: In this example, we are going to invoke class methods.
class Animal
def dog
puts "Dog is barking"
end
def enternames(one, two)
puts one
puts two
end
end
animal = Animal. new
animal.dog
animal.enternames( "Cat" , "Elephant" )
animal.send :dog
animal.send :enternames , "Cat" , "Elephant"
|
Output:
Dog is barking
Cat
Elephant
Dog is barking
Cat
Elephant
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!