How to invoke methods in Ruby?


Methods in Ruby, as in other programming languages, bundle one or more repeatable statements into a single unit. Method names in Ruby should begin with a lowercase letter. If you begin a method name with an uppercase letter, Ruby might think that it is a constant and hence can parse the call incorrectly.

Methods should be defined before calling them, otherwise Ruby will raise an exception for invoking an undefined method.

There are different ways in which we can invoke methods in Ruby. When we are invoking a method in Ruby, the use of the parentheses is optional and hence they can be omitted.

In this article, we will explore the different ways of invoking a method in Ruby.

Invoking a Method with No Arguments

In this example, I am invoking a method that doesn't have any arguments. Consider the first code shown below.

Example

Consider the code shown below.

string1 ='You can shake the world in a gentle way.'

# "length" invoked on object
puts string1

Output

It will produce the following output.

You can shake the world in a gentle way.

Invoking a Method with a Single Argument

In this example, we are invoking a method that takes a single argument. Consider the second code shown below.

Example

Consider the code shown below.

# "sqrt" invoked on object
# Math with one argument
num = Math.sqrt(9)
puts "Square Root of 9:"
puts num

Output

It will produce the following output.

Square Root of 9:
3.0

Invoking a Method with Two Arguments

In this example, we are invoking a method that takes two arguments. Consider the third code shown below.

Example

Consider the code shown below.

def subtract(a, b)
   # 'subtract' method definition
   a - b
end

# Calling method 'subtract'
c = subtract(20, 10)
d = subtract(90, 45)
puts c
puts d

Output

It will produce the following output.

10
45

Invoking a Class Method

In this example, we are invoking a class method. Consider the code shown below −

Example

Consider the code shown below.

# 'Vehicle' class definition
class Vehicle
   # 'cat' function definition
   # having no arguments
   def function1
      puts "The Bus is Moving at a Constant Speed."
   end
end

# Create a new instance of Animal
obj = Vehicle.new

# Instance method invocation
obj.function1

# Class method call using send method
obj.send :function1

Output

It will produce the following output.

The Bus is Moving at a Constant Speed.
The Bus is Moving at a Constant Speed.

Updated on: 12-Apr-2022

549 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements