TExcelTAD
Home › Ruby › Ruby Method Arguments

Ruby Method Arguments

Ruby's methods can accept arguments in many shapes: required, optional with defaults, named keyword arguments, and variable-length lists collected with splats. Choosing the right kind makes a method easy and safe to call.

Default values

Give a parameter a default and callers may leave it out:

ruby · try it yourself
def brew(drink, size = "medium", sugar = 0)
  "#{size} #{drink}, #{sugar} sugar"
end

puts brew("tea")
puts brew("coffee", "large")
puts brew("cocoa", "small", 2)
medium tea, 0 sugar
large coffee, 0 sugar
small cocoa, 2 sugar

The weakness of positional defaults: to set sugar you must also pass size. Keyword arguments solve that.

Keyword arguments

Keyword arguments are named at the call site, so order doesn't matter and the call explains itself:

ruby · try it yourself
def book_table(name:, guests: 2, time: "19:00", terrace: false)
  spot = terrace ? "terrace" : "inside"
  "#{name}: #{guests} people at #{time} (#{spot})"
end

puts book_table(name: "Okafor")
puts book_table(time: "20:30", name: "Lund", terrace: true)
puts book_table(name: "Ruiz", guests: 6)
Okafor: 2 people at 19:00 (inside)
Lund: 2 people at 20:30 (terrace)
Ruiz: 6 people at 19:00 (inside)

name: without a default is a required keyword. Forgetting it, or passing an unknown keyword, raises an error with a clear message:

ruby · try it yourself
def connect(host:, port: 80)
  "#{host}:#{port}"
end

begin
  connect(port: 8080)
rescue ArgumentError => e
  puts e.message
end

begin
  connect(host: "example.com", timeout: 5)
rescue ArgumentError => e
  puts e.message
end
missing keyword: :host
unknown keyword: :timeout

Splat: any number of positional arguments

A parameter prefixed with * collects all remaining positional arguments into an array:

ruby · try it yourself
def average(*numbers)
  return 0 if numbers.empty?
  numbers.sum.fdiv(numbers.size)
end

p average(4, 8)
p average(1, 2, 3, 4, 5)
p average

def tag(name, *classes)
  "<#{name} class=\"#{classes.join(' ')}\">"
end
puts tag("div", "card", "shadow", "rounded")
6.0
3.0
0
<div class="card shadow rounded">

Double splat: any keyword arguments

**options collects unknown keyword arguments into a hash:

ruby · try it yourself
def log(message, level: :info, **context)
  extras = context.map { |k, v| "#{k}=#{v}" }.join(" ")
  "[#{level.upcase}] #{message} #{extras}".strip
end

puts log("Server started")
puts log("Login failed", level: :warn, user: "eve", ip: "10.0.0.7")
[INFO] Server started
[WARN] Login failed user=eve ip=10.0.0.7

Splatting when calling

The same * and ** operators unpack an array or hash into arguments at the call site:

ruby · try it yourself
def point(x, y, z)
  "(#{x}, #{y}, #{z})"
end

coords = [3, 4, 5]
puts point(*coords)

def greet(name:, greeting: "Hello")
  "#{greeting}, #{name}!"
end

opts = {name: "Yuki", greeting: "Konnichiwa"}
puts greet(**opts)
(3, 4, 5)
Konnichiwa, Yuki!

Block argument

A method can also receive a block explicitly with &block. It becomes a Proc object you can store or pass along (more in Blocks & yield):

ruby · try it yourself
def repeat(times, &action)
  times.times { |i| action.call(i) }
end

repeat(3) { |i| puts "ping #{i}" }
ping 0
ping 1
ping 2

Order of parameters

When combined, parameters must appear in this order:

ruby
def full(required, optional = 1, *rest, keyword:, opt_kw: 2, **opts, &block)
end
Kind Syntax Inside the method
Required positional a value
Optional positional a = 1 value or default
Rest positional *args Array
Required keyword key: value
Optional keyword key: 1 value or default
Rest keywords **opts Hash
Block &blk Proc or nil

Shorthand: hash value omission

Since Ruby 3.1, when a local variable has the same name as the keyword, you can omit the value:

ruby · try it yourself
def profile(name:, city:)
  "#{name} lives in #{city}"
end

name = "Noor"
city = "Cairo"
puts profile(name:, city:)
Noor lives in Cairo

Tip: Prefer keyword arguments when a method takes more than two or three arguments, or when any argument is a boolean flag. send_mail(to: x, urgent: true) is much clearer than send_mail(x, true).

Test yourself

What does *items in a method definition do?

  1. Makes items required
  2. Collects all remaining positional arguments into an array
  3. Multiplies the arguments
  4. Declares a pointer

Given def f(size:, color: "red"), which call is valid?

  1. f("L")
  2. f(color: "blue")
  3. f(size: "L")
  4. f()

What does **opts collect?

  1. Extra keyword arguments as a Hash
  2. Extra positional arguments as an Array
  3. The block
  4. Only symbols