Ruby: Function Optional Parameter

By Xah Lee. Date:

The following is a example of defining a function.

Function name should start with lowercase.

# -*- coding: utf-8 -*-
# ruby

# function with no parameter
def ff
  4
 # return 4    # return is optional. If no return, returns last expression
end

p ff # 4

If a function definition does not return, it returns last expression. In Ruby, everything has a return value.

# -*- coding: utf-8 -*-
# ruby

# function with 2 parameters
def gg (aa, bb)
  aa + bb
end

p gg 3, 4 # 7

Unspecified Number of Positional Parameters

To define unspecified number of parameters, use *name as last item. Your function will receive it as a array named name.

# -*- coding: utf-8 -*-
# ruby

# function with unspecified number of arguments.
# Use *‹name›
# Your function will receive a array of ‹name›
def ff(*xx)
  xx[0] # first arg
  xx[1] # second arg
  xx # return the array
end

p ff(3) # [3]
p ff(3, 4, 5) # [3, 4, 5]

Optional Parameters

A function can have optional Parameters. When a function call doesn't supply enough arguments, default values are used.

Ruby doesn't have named parameters.

# -*- coding: utf-8 -*-
# ruby

# Defining optional parameters.
def ff(x, y = 7, z = 8)
  [x, y, z] # returns a array of the arguments received
end

p ff(3) # [3, 7, 8]

p ff(3, 2) # [3, 2, 8]

p ff(3, 5, 6) # [3, 5, 6]