Optional Method Parameters in Ruby

Ruby allows programmers to specify optional method parameters through the use of default parameter values. For example:

def some_method( a = ‘testing’, b = ‘optional’, c = ‘params’ )

You can call the above method in any of the following ways:

some_method ( ‘hello’ )
some_method ( ‘hello’, ‘world’ )

This method of specifying optional parameters is not very flexible, because, you can’t specify the parameters out of order or skip the parameters that appear before the parameter you specify. For example, in the method definition given above, there is no way to specify value for parameter b without also specifying the value for parameter a.

To work around this issue, there is a mechanism called Named parameters which is often used by experienced Ruby programmers. Consider the following example:

def method(opts={})
o = {
:a => ‘testing,
:b => ‘optional’,
:c => ‘params’

Now, you can call the above method in following ways:

method( :b => ‘hello world’ )
method( :c => ‘good’, :b => ‘feels’ )

The above method declares a hash named o that contains the default parameter values. The default parameter hash is merged with the method parameters specified in the method call by using the merge function (which uses the value of the second hash, in case of duplicate keys).

  1. No comments yet.

Leave a reply


8 × three =