๐ŸŽ“ A1Learner
๐Ÿ”
0 of 28 lessons completed

Ruby Argument Delegation

Some methods exist only to pass their arguments along. The (...) marker forwards every argument at once, so the forwarder names nothing.

Forward everything at once

The wrap method declares no parameters of its own. The (...) marker carries the word and the keyword straight into label.

def label(name, mark:)
  "#{name}#{mark}"
end

def wrap(...)
  label(...)
end
puts wrap "ruby", mark: "!"
puts wrap "gem", mark: "?"

Keywords arrive whole

The helper has two keyword parameters with defaults. The forwarder passes whatever the caller gave, and the defaults fill the rest.

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

def wrap(...)
  greet(...)
end
puts wrap "Ana"
puts wrap "Ana", greeting: "Hi"
puts wrap "Bo", punct: "."

super with the same arguments

The override prints a line first, then super(...) hands the original name to the parent method. The parent builds the answer as usual.

class Greeter
  def greet(name)
    "Hello, #{name}"
  end
end

class LoudGreeter < Greeter
  def greet(...)
    puts "One greeting coming up"
    super(...)
  end
end
greeter = LoudGreeter.new
puts greeter.greet "Ana"

Example

def record(event, level: "info")
  "#{level}: #{event}"
end

def log(...)
  record(...)
end

class Base
  def report(title)
    "Report: #{title}"
  end
end

class TimedReport < Base
  def report(...)
    puts "Preparing report"
    super(...)
  end
end
puts log "Saved file"
puts log "Failed save", level: "error"
report = TimedReport.new
puts report.report "Weekly"

Key points

  • The (...) marker in a parameter list stands for every argument at once.
  • Inside the body, (...) hands those arguments to another call whole.
  • Positional and keyword arguments travel together, unchanged.
  • super(...) sends the same arguments up to the parent method.
  • A forwarder with (...) names no parameters of its own.

In this example, log forwards each event and level into record without naming either one. TimedReport then adds a line before super(...) passes the title up. Both forwarders stay one line long.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does (...) hand to the helper?