Argument forwarding and anonymous parameters

suggest change

Wrappers, decorators, proxies and delegating methods all have the same job: take whatever arguments they were called with and pass them on to another method. Since Ruby 3.0 separated positional and keyword arguments, doing that by hand means writing *args, **kwargs, &block twice:

def target(*args, **kwargs, &block)
  p args:, kwargs:, block: block&.call
end

def old_style(*args, **kwargs, &block)
  target(*args, **kwargs, &block)
end

def new_style(...)
  target(...)
end

old_style(1, 2, color: "red") { "yielded" }
new_style(1, 2, color: "red") { "yielded" }
new_style
{args: [1, 2], kwargs: {color: "red"}, block: "yielded"}
{args: [1, 2], kwargs: {color: "red"}, block: "yielded"}
{args: [], kwargs: {}, block: nil}

Ruby has added several shorthands for this over a few releases:

Syntax Meaning Since
def m(...) / other(...) forward all arguments and the block 2.7
def m(a, ...) / other(:x, ...) leading arguments before ... 3.0
def m(&) / other(&) anonymous block parameter 3.1
def m(*) / other(*) anonymous rest (positional) parameter 3.2
def m(**) / other(**) anonymous keyword rest parameter 3.2

All examples below were run with Ruby 4.0.

Forwarding everything with ...

A method declared with (...) accepts any arguments and any block. Inside it, ... in a call passes all of them on unchanged: positional arguments, keyword arguments and the block. Keywords stay keywords and a hash passed positionally stays positional, which is exactly what you want in a delegating method.

... works well with endless method definitions:

class Playlist
  def initialize = @songs = []
  def add(...) = @songs.push(...)
  def each(...) = @songs.each(...)
end

list = Playlist.new
list.add("Blue in Green", "So What")
list.each { puts it }
p list.each.to_a
Blue in Green
So What
["Blue in Green", "So What"]

each without a block returns an enumerator, because @songs.each was called with no block either.

Leading arguments

Since Ruby 3.0 the method can declare ordinary parameters before ..., and a call can pass extra arguments before .... That covers the common "fix the first argument" case:

def log(level, message, **context)
  puts "[#{level.upcase}] #{message} #{context unless context.empty?}".rstrip
end

def info(...) = log(:info, ...)
def warn_once(message, ...)
  @warned ||= {}
  return if @warned[message]
  @warned[message] = true
  log(:warn, message, ...)
end

info("server started", port: 4567)
warn_once("disk almost full", free: "2%")
warn_once("disk almost full", free: "1%")
info("done")
[INFO] server started {port: 4567}
[WARN] disk almost full {free: "2%"}
[INFO] done

warn_once needs to look at message, so it names it and forwards the rest. Leading parameters can be required or optional (def m(a, b = 1, ...)), and the call can use any positional expression before ..., including a splat: other(*list, ...).

What ... can't do

... is all or nothing. These are compile-time errors:

def greet = puts(...)
e1.rb:1: syntax error found (SyntaxError)
> 1 | def greet = puts(...)
    |                  ^~~ unexpected ... when the parent method is not forwarding
def connect(*args, ...) = open(*args, ...)
e2.rb:1: syntax error found (SyntaxError)
> 1 | def connect(*args, ...) = open(*args, ...)
    |                    ^~~ ... after rest argument
def wrap(...) = puts(...) { "extra block" }
e3.rb:1: syntax error found (SyntaxError)
> 1 | def wrap(...) = puts(...) { "extra block" }
    |                           ^~~~~~~~~~~~~~~~~ both block arg and actual block given; only one block is allowed

... also isn't available for blocks and lambdas: proc { |...| } and ->(...) {} are syntax errors. Use the anonymous parameters from the next sections when you need more control.

Always use parentheses

A call with ... must use parentheses. Without them Ruby parses target ... as an endless range starting at target, calls target with no arguments and only prints a warning:

def target(*args, **kw, &b) = p(args:, kw:)
def m1(...)
  target ...
end
m1(1, 2)
t9.rb:3: warning: ... at EOL, should be parenthesized?
{args: [], kw: {}}

Anonymous block parameter &

When a method only passes its block to another method, the block doesn't need a name. Ruby 3.1 lets you write & in the parameter list and & in the call:

def each_pair_of(list, &)
  list.each_slice(2, &)
end

each_pair_of([1, 2, 3, 4]) { |a, b| puts "#{a} + #{b} = #{a + b}" }
p each_pair_of([1, 2, 3]).to_a

def with_block(&)
  p block_given?
  yield 10 if block_given?
end
with_block { |x| p x * 2 }
with_block
1 + 2 = 3
3 + 4 = 7
[[1, 2], [3]]
true
20
false

block_given? and yield work as usual. The block can't be stored, though: if you need it as an object (@callback = block), give it a name. & is the most common of the anonymous parameters in practice. The coding conventions article uses it to make a class Enumerable with def each(&) = @songs.each(&).

Anonymous * and **

Ruby 3.2 did the same for the rest parameters (see the splat operator). * collects extra positional arguments and ** extra keyword arguments, and both can be passed on in a call. Unlike ..., they can be mixed freely with named parameters, extra arguments and a literal block:

def fetch(url, timeout: 30, retries: 0)
  puts "GET #{url} timeout=#{timeout} retries=#{retries}"
end

def fetch_with_defaults(*, **)
  fetch(*, timeout: 5, **)    # later keywords win
end

def fetch_patient(*, retries: 3, **)
  fetch(*, retries:, **)      # named keyword plus anonymous rest
end

fetch_with_defaults("/a")
fetch_with_defaults("/b", timeout: 60)
fetch_patient("/c")
fetch_patient("/d", timeout: 1, retries: 0)
GET /a timeout=5 retries=0
GET /b timeout=60 retries=0
GET /c timeout=30 retries=3
GET /d timeout=1 retries=0

fetch_with_defaults changes a default: timeout: 5 comes first, so a timeout: passed by the caller (inside **) overrides it. fetch_patient pulls one keyword out by name and forwards everything else. Neither is possible with ....

Anonymous rest parameters can also be used in array and hash literals, which is the only way to look at their contents:

class NullLogger
  def info(*, **) = nil
  def warn(*, **) = nil
  def method_missing(*) = self
  def respond_to_missing?(*) = true
end

logger = NullLogger.new
p logger.info("ignored", user: 42)
p logger.anything.chained.calls.equal?(logger)

def args_of(*) = [*]
def opts_of(**) = {**}
def both(*, **) = [[*], {**}]
p args_of(1, 2, 3)
p opts_of(a: 1, b: 2)
p both(1, x: 2)
nil
true
[1, 2, 3]
{a: 1, b: 2}
[[1], {x: 2}]

The null object above shows the other common use: (*, **) says "accept and ignore any arguments". It's shorter than (*_args, **_opts) and linters don't complain about unused variables. Stubs in tests use the same trick, see mocks and test doubles.

Each anonymous argument in a call needs the matching anonymous parameter. ** in a method that only declared * is an error, and so is & in a method that declared &block:

def first(*) = puts(**)
e4.rb:1: syntax error found (SyntaxError)
> 1 | def first(*) = puts(**)
    |                     ^~ unexpected `**`; no anonymous keyword rest parameter

A method declared with (...) doesn't define *, ** or & for you: def m(...) = other(*, ...) or other(&) are errors in Ruby 4.0. Pick one style per method.

* alone drops keywords

(*) without ** behaves like (*args): keywords passed by the caller are collected into a hash at the end of the array, and forwarding that array passes the hash positionally. Compare the three forms:

def target(*args, **kw) = p(args:, kw:)

def fwd_dots(...) = target(...)
def fwd_anon(*, **) = target(*, **)
def fwd_rest(*) = target(*)

opts = {verbose: true}
fwd_dots(1, opts)       # a hash passed positionally stays positional
fwd_dots(1, **opts)
fwd_anon(1, **opts)
fwd_rest(1, **opts)     # keywords collected into * become a positional hash
{args: [1, {verbose: true}], kw: {}}
{args: [1], kw: {verbose: true}}
{args: [1], kw: {verbose: true}}
{args: [1, {verbose: true}], kw: {}}

To forward faithfully, use ... or (*, **, &). Libraries that had to support both Ruby 2.x and 3.x used ruby2_keywords instead. It flags a *args method so that a trailing keywords hash is passed on as keywords again:

def connect(host, port: 80) = puts("#{host}:#{port}")

def plain(*args) = connect(*args)
ruby2_keywords def flagged(*args) = connect(*args)
def modern(...) = connect(...)

modern("example.com", port: 443)
flagged("example.com", port: 443)
begin
  plain("example.com", port: 443)
rescue ArgumentError => e
  puts "ArgumentError: #{e.message}"
end
example.com:443
example.com:443
ArgumentError: wrong number of arguments (given 2, expected 1)

New code doesn't need ruby2_keywords, ... and (*, **, &) do the job without flags.

Anonymous parameters inside blocks

A block inside the method can use the method's anonymous parameters, as long as the meaning is unambiguous:

def apply(*, &)
  [10, 20].map { |x| send(*, x, &) }
end

def scale(factor, x) = yield(x * factor)

p apply(:scale, 3) { it + 1 }
[31, 61]

... can be used inside blocks the same way. It's ambiguous when the block itself declares an anonymous parameter of the same kind, for example { |*| ... }. Then * in the block could mean either one, and Ruby refuses to compile it:

def each_item(*, &)
  [1, 2].each { |*| puts(*) }
end
e5.rb:2: syntax error found (SyntaxError)
  1 | def each_item(*, &)
> 2 |   [1, 2].each { |*| puts(*) }
    |                          ^ unexpected `*`; anonymous rest parameter is also used within block
  3 | end

The same applies to |**|, |&| and lambdas such as ->(*) { other(*) }. The fix is to name one of the two. This rule changed a few times: Ruby 3.3.0 rejected every use of an anonymous parameter inside a block, and later releases (3.3.1 and 3.4+) went back to rejecting only the ambiguous case shown above.

Two related limits:

Introspection

Method#parameters reports anonymous parameters with the names :*, :** and :&. A (...) method looks exactly like (*, **, &):

def a(...) = nil
def b(x, ...) = nil
def c(*, **, &) = nil
def d(*args, **opts, &blk) = nil
def e(&) = nil
p method(:a).parameters
p method(:b).parameters
p method(:c).parameters
p method(:d).parameters
p method(:e).parameters
p [method(:a).arity, method(:b).arity, method(:c).arity]
def f(*) = binding.local_variables
p f(1, 2)
[[:rest, :*], [:keyrest, :**], [:block, :&]]
[[:req, :x], [:rest, :*], [:keyrest, :**], [:block, :&]]
[[:rest, :*], [:keyrest, :**], [:block, :&]]
[[:rest, :args], [:keyrest, :opts], [:block, :blk]]
[[:block, :&]]
[-1, -2, -1]
[]

The anonymous parameters aren't local variables, so binding.local_variables and eval can't see them.

Delegation and decorators

The main use of forwarding is code that sits between a caller and the real implementation. Here's a proxy built on method_missing that records which methods were called. method_missing(name, ...) forwards the arguments and the block of any call, and a bare super passes the original arguments to the default method_missing:

class Recorder
  def initialize(target)
    @target = target
    @calls = []
  end
  attr_reader :calls

  def method_missing(name, ...)
    return super unless @target.respond_to?(name)

    @calls << name
    @target.public_send(name, ...)
  end

  def respond_to_missing?(name, include_private = false)
    @target.respond_to?(name, include_private) || super
  end
end

list = Recorder.new([3, 1, 2])
p list.sort
p list.map { it * 10 }
p list.each_slice(2).to_a
p list.respond_to?(:push)
p list.calls
list.frobnicate
[1, 2, 3]
[30, 10, 20]
[[3, 1], [2]]
true
[:sort, :map, :each_slice]
t7.rb:9:in 'Recorder#method_missing': undefined method 'frobnicate' for an instance of Recorder (NoMethodError)
	from t7.rb:26:in '<main>'

For a decorator that wraps an existing method, Module#prepend and super are the cleanest option. Inside a method with ... or anonymous parameters, a bare super (no parentheses) forwards all the arguments and the block, the same as super(...), so the decorators don't need to know the wrapped method's signature:

class FlakyGateway
  def initialize = @failures = 2

  def charge(amount, currency: "USD")
    if (@failures -= 1) >= 0
      puts "charge #{amount} #{currency}: timeout"
      raise IOError, "timeout"
    end
    puts "charge #{amount} #{currency}: ok"
    :ok
  end
end

module Retrying
  def charge(*, **)
    attempts = 0
    begin
      attempts += 1
      super
    rescue IOError
      retry if attempts < 3
      raise
    end
  end
end

module Timing
  def charge(...)
    started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
    result = super
    elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
    puts "charge took #{elapsed < 1 ? "under a second" : "too long"}"
    result
  end
end

FlakyGateway.prepend(Retrying, Timing)
p FlakyGateway.ancestors.first(3)
p FlakyGateway.new.charge(10, currency: "EUR")
[Retrying, Timing, FlakyGateway]
charge 10 EUR: timeout
charge 10 EUR: timeout
charge 10 EUR: ok
charge took under a second
:ok

A decorator generated for any method name has to use define_method, and there neither ... nor a bare super work:

class Base
  def run(...) = puts("define_method needs explicit args")
end
class Sub < Base
  define_method(:run) { |*| super }
end
Sub.new.run(1)
t15.rb:5:in 'block in <class:Sub>': implicit argument passing of super from method defined by define_method() is not supported. Specify all arguments explicitly. (RuntimeError)
	from t15.rb:7:in '<main>'

So a class macro like log_calls falls back to named *args, **kwargs, &block:

module LogCalls
  def log_calls(*names)
    wrapper = Module.new do
      names.each do |name|
        define_method(name) do |*args, **kwargs, &block|
          puts "-> #{name} #{args.inspect} #{kwargs.inspect}"
          super(*args, **kwargs, &block)
        end
      end
    end
    prepend wrapper
  end
end

class Mailer
  extend LogCalls
  log_calls :deliver

  def deliver(to, subject:, cc: nil) = "sent #{subject.inspect} to #{to}"
end

p Mailer.new.deliver("ada@example.com", subject: "Hi", cc: "bob@example.com")
-> deliver ["ada@example.com"] {subject: "Hi", cc: "bob@example.com"}
"sent \"Hi\" to ada@example.com"

For plain delegation of a fixed list of methods, the standard library's Forwardable (def_delegators :@songs, :each, :size) is often simpler still. See composition and delegation.

Which form to use

Avoid (*) on its own when forwarding to a method that takes keywords, since it turns keywords into a positional hash. When in doubt, ... is the safe choice.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents