Ruby: Define Function

By Xah Lee. Date: . Last updated: .

The following is a example of defining a function.

Function name should start with lowercase.

# ruby

# function with no parameter
def ff
  4
end

p ff() == 4

# paren can be omitted
p ff == 4

function with 1 param:

# ruby

# function with 1 param
def f(x) x+1 end

p f(4) == 5

function with 2 parameters:

# ruby

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

p gg(3, 4) == 7

The keyword return can be used to return value and exit code. If no return, returns last expression.

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.

# 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.

# ruby

# function with default value
def f(x = 3) x+1 end

puts f == 4
# ruby

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

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

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

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

Unspecified Number of Parameters

# ruby

# example of defining a function with unspecified number of parameters
def ff(*xx)
 xx
end

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

Ruby Tutorial

Print

String

Types

Variable

Boolean

Branching

Loop, Iteration

Data Structure

Function

Misc