Ruby - Default Argument Value

Introduction

Ruby can 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.

Demo

def aMethod( a=10, b=20 )
   return a, b# from  ww w.j  a v  a 2s. c om
end
p( aMethod )            #=> displays: [10,  20]
p( aMethod( 1 ))        #=> displays: [1, 20]
p( aMethod( 1, 2 ))     #=> displays: [1, 2]

Result

Related Topics