Methods

Methods are called as Functions. Methods are used to execute specific set of instructions

For example,

  • File Menu in Word has different operations like Save, Open etc.,
  • Save is used to specifically save the document and contains corresponding code for it.
  • Open command is used to open the document.
Functions take arguments and have return type.

Arguments are like an input given to the function and return type is the output of the function.

Return type can be two types in ruby:

  1. By using the expression
  2. By using return keyword.

Syntax of method:

def methodname(arguments)
statements
return
end

defining a method in Ruby

In the above code, there is a method named square with one argument. A variable named number is assigned with the value of 3. Another variable called numbersqr is assigned with the value returned by the function. Here, we call the function by specifying the name and passing the argument.

square(number). It is called function calling statement.

The variable number is passed to the function which is assigned to the local variable num in the function, the number is multiplied and the function returns the value which is assigned to the variable numbersqr.

This is the output of the above program :

defining a method in Ruby

The value 9 is returned from the function and assigned to variable numbersqr and displayed using print method. In this example, the return type of the function is using expression.


Method with more than one parameter

defining a method with more than one parameter in Ruby

In this program, there are two methods square and power. Power method takes two arguments. This method returns the value after raising the value present in the base variable to the value present in the exp variable. This method explicitly returns the value. That is, the value is returned using return keyword.

def power (base, exp)
product = 1
while exp > 0
product *= base
exp -= 1
end
return product
end

When this function is called by passing the following parameters: power (3, 3). It returns the value of 3 raised to the power 3.

In this program, the function calling statement is written inside print method. This specifies that function called be anywhere in the program.

First, the square method is called, it returns the value and stored in the variable numbersqr. Now, when calling power method, we are passing the variables numbersqr and number. Therefore, the value of numbersqr^number is returned.

In our case, 9^3 or 9*9*9 which is 729 is returned from the function.

defining a method in Ruby