Methods in Ruby

A method is another name for a function. Programmers with a different background than Ruby might use these terms interchangeably. A method is a subroutine that performs a specific operation. The use of methods implements the reuse of code and decreases the length of programs significantly. Defining a method is easy, and their definition starts with the def keyword and ends with the end statement. Let's consider a simple program to understand how they work for example, printing out the square of 50:

def print_data(par1) 
square = par1*par1 
return square 
end 
answer = print_data(50) 
print(answer)  

The print_data method receives the parameter sent from the main function, multiplies it with itself, and sends it back using the return statement. The program saves this returned value in a variable named answer, and prints the value. We will use methods heavily in the latter part of this chapter as well as in the next few chapters.