Ruby Methods

From Techotopia
Jump to: navigation, search
PreviousTable of ContentsNext
Ruby Number Classes and ConversionsRuby Ranges


Purchase and download the full PDF and ePub editions of this Ruby eBook for only $8.99

Buy eBook


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 Method

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.


Passing a Variable Number of Arguments to a Method

In the previous section of this chapter we looked at specifying a fixed number of arguments accepted by a method. Sometimes we don't always know in advance how many arguments will be needed. Ruby addresses this by allowing a method to be declared with a variable number of arguments. This achieved by using *args when declaring the method. The arguments passed to the method are then placed in an array where they may be accessed in the body of the method (see the Understanding Ruby Arrays for details on using arrays):

irb(main):062:0> def displaystrings( *args )
irb(main):063:1>         args.each {|string| puts string}
irb(main):064:1> end
=>nil

displaystrings("Red")
Red

displaystrings("Red", "Green")
Red
Green

irb(main):067:0> displaystrings("Red", "Green", "Blue")
Red
Green
Blue

As you can see, the method can handle any number of arguments passed through.

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 values 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.

Ruby Method Aliases

Ruby allows a method to be aliased, thereby creating a copy of a method with a different name (although invoking the method with either name ultimately calls the same object). For example:

irb(main):001:0> def multiply(val1, val2 )
irb(main):002:1>      result = val1 * val2
irb(main):003:1>      return result
irb(main):004:1> end
=> nil

alias docalc multiply
=> nil

docalc( 10, 20 )
=> 200

multiply( 10, 20 )
=> 200


Purchase and download the full PDF and ePub editions of this Ruby eBook for only $8.99

Buy eBook



PreviousTable of ContentsNext
Ruby Number Classes and ConversionsRuby Ranges