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. Unicode 💎
  5. Quote String
  6. Quote Long String
  7. Format String
  8. String Operations
  9. True, False
  10. “if then else”
  11. for, while, Loop
  12. List
  13. Loop Thru List
  14. Hash Table
  15. Function Optional Parameter
  16. Map f to List
  17. Complex Numbers
  18. Intro to Reading Ruby Doc: What's M, C, ::, # ?
  19. Predefined Global Variables
  20. What's RVM, Gem, Rake, Bundler, RDoc, ri, irb?