Methods are also called as Functions. Methods are used to execute specific set of instructions
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:
Syntax of method:
def methodname(arguments) statements return end
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.
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
This is the output of the above program :
The value 9 is returned from the function and assigned to variable
numbersqr and displayed using
In this program, there are two methods
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
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
number. Therefore, the value of
numbersqr ^ number is returned.
In our case,
9*9*9 which is 729 is returned from the function.