Changes

Jump to: navigation, search

Ruby Methods

945 bytes added, 16:29, 30 November 2007
Passing Arguments to a Function
</pre>
== Passing Arguments to a Function 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:
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 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):
 
<pre>
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
</pre>
 
As you can see, the method can handle any number of arguments passed through.
== Returning a Value from a Function ==

Navigation menu