Default and Multiple Arguments

Ruby lets you specify default values for arguments. Default values can be assigned in the parameter list of a method using the usual assignment operator:

def aMethod( a=10, b=20 )

If an unassigned variable is passed to that method, the default value will be assigned to it. If an assigned variable is passed, however, the assigned value takes precedence over the default. Here I use the p() method to inspect and print the return values:

def aMethod( a=10, b=20 )
   return a, b
end

p( aMethod )            #=> displays: [10,  20]
p( aMethod( 1 ))        #=> displays: [1, 20]
p( aMethod( 1, 2 ))     #=> displays: [1, 2]

In some cases, a method may need to be capable of receiving an uncertain number of arguments—say, for example, a method that processes a variable-length list of items. In this case, you can “mop up” any number of trailing items by preceding the final argument with an asterisk:

default_args.rb

def aMethod( a=10, b=20, c=100, *d )
   return a, b, c, d
end

p( aMethod( 1,2,3,4,6 ) )     #=> displays: [1, 2, 3, [4, 6]]
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.245.233