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]

If you have a question, put $5 at patreon and message me.

  1. Ruby Basics
  2. Doc Lookup
  3. Print Version String
  4. What's RVM, Gem, Rake, Bundler, RDoc, ri, irb?

  1. Unicode 💎
  2. Quote String
  3. Quote Long String
  4. Format String
  5. String Operations
  6. True, False
  7. “if then else”
  8. for, while, Loop
  9. List
  10. Loop Thru List
  11. Hash Table
  12. Function Optional Parameter
  13. Map f to List
  14. Complex Numbers
  1. Intro to Reading Ruby Doc: What's M, C, ::, # ?
  2. Predefined Global Variables