Ruby Methods
Ruby methods provide a way to organize code and promote re-use. Rather than create long sections of Ruby code, the code is instead organized into logical groups that can be called when needed and re-used without having to re-write the same code over and over. Methods are simple to use, in fact you only need to do two things with a method, declare it and call it.
Declaring and Calling a Ruby Method
The syntax of a Ruby method is as follows:
def name( arg1, arg2, arg3, ... ) .. ruby code .. return value end
The name specifies how we will refer to this method when we call it. The args specify values that are passed through to the method to be processed. The ruby code section represents the body of the function that performs the processing. The optional return statement allows a value to be returned to the section of code which called the method (for example to return a status or the result of a calculation).
The following simple example shows a method defined and called. All the method does is display a string:
def saysomething() puts "Hello" end saysomething
Passing Arguments to a Function
The above example did not pass any arguments through to the function. Commonly a function is designed to perform some task on a number of arguments as in the following example:
def multiply(val1, val2 ) result = val1 * val2 puts result end multiply( 2, 10 ) multiply( 4, 20 ) multiply( 10, 40 ) multiply( 6, 7 )
In this example, the method is called multiple times, passing through arguments that are then used in the method to perform a calculation on the arguments, displaying the result. To achieve this without methods it would be necessary to repeat the code in the method 4 times over. Clearly, placing the code in a method and re-using it over and over is a much more efficient approach.
Next we need to look at how a method might return a value.
Returning a Value from a Function
The return statement is used to return a value from a method and the assignment (=) method is used to accept that return value at the point that the method is called.
As an example, we will declare a method which multiplies two arguments and returns the result:
def multiply(val1, val2 ) result = val1 * val2 return result end value = multiply( 10, 20 ) puts value
The above example passes 10 and 20 through to the multiply method. The method multiplies these two value and returns the result. The assignment method (=) assigns the result to the variable value which is then displayed using puts.
It is important to note that a method can return one, and only one value or object. If you need to return multiple values, consider placing the results in an array and returning the array.