Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 134 ยท Methods and Blocks

Method Arguments

Master Ruby method parameters - positional, optional, splat, keyword, required keyword, double splat, block arguments and argument forwarding with ... and anonymous * ** &.

Ruby gives you an unusually rich set of ways to declare what a method accepts. You can have required and optional positional parameters, collect any number of extras with *, ask for named arguments with name:, collect unknown keywords with **, capture a block with &, and forward everything to another method with .... Used well, these make calls read like sentences: connect(host: "db", port: 5432, timeout: 3).

This lesson walks through each kind in the order Ruby requires them in a definition, shows the errors you get when a call does not match, and ends with the modern forwarding syntax of Ruby 3.2 and later. Terminology: parameters are the names in the definition; arguments are the values you pass in the call.

Positional parameters

The simplest kind. Arguments are matched by position, and the count must match exactly.

Ruby Wrong number of arguments (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first call prints 12. The second is rescued and prints rescued: wrong number of arguments (given 1, expected 2). The third is not, and the program ends with main.rb:1:in 'Object#area': wrong number of arguments (given 3, expected 2) (ArgumentError), followed by a caller: and a callee: snippet that point at the call (line 13) and at the def (line 1). Ruby is strict: no silent nil for missing arguments, unlike JavaScript.

Optional parameters (default values)

Give a parameter a default with =. The default is evaluated each time the method is called without that argument, and it can use earlier parameters.

Ruby Default values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

A fresh [] is created on every call, so the two stamp calls do not share state. That is a nice difference from Python, where a mutable default is created once. Optional parameters fill in from left to right, so you cannot skip the second one and give the third positionally; that is one reason keyword arguments exist.

Splat: any number of arguments

A parameter prefixed with * collects the remaining positional arguments into an array.

Ruby Splat parameters and splat calls

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

A splat in a definition gathers; a splat in a call spreads. The splat parameter can sit in the middle of the list: required parameters after it take their values from the end. Both log("INFO") with no messages and total with no arguments work, because the array is simply empty.

Keyword arguments

Named parameters end with a colon. The caller writes the names, so the order does not matter and the call documents itself.

Ruby Keyword arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

host: (nothing after the colon) is a required keyword; port: 5432 is optional with a default. Leaving out a required keyword raises missing keyword: :host, and passing an unknown one raises unknown keyword: :user. Typos in option names are caught immediately, which is a real advantage over options hashes.

Prefer keyword arguments whenever a method takes more than two or three parameters, or when a value's meaning is not obvious at the call site: resize(img, 200, 100, true) versus resize(img, width: 200, height: 100, crop: true).

Passing a hash as keywords

Use ** in the call to spread a hash into keywords. Since Ruby 3.0, keywords and positional hashes are separate: a hash is no longer converted automatically.

Ruby Double splat in a call

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Passing the bare hash raises wrong number of arguments (given 1, expected 0; required keyword: host). The last line shows the hash/keyword shorthand added in Ruby 3.1: connect(host:, port:) means connect(host: host, port: port) when local variables have the same names.

Collecting unknown keywords with **

A parameter starting with ** gathers all other keywords into a hash. It is common for wrappers and configuration:

Ruby Double splat parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Note that build_tag("img", src: ...) assigns "img" to name and the keywords to attributes; content stays nil. If you want to forbid keywords completely, write **nil.

Block parameters

Every method can receive a block without declaring it, and call it with yield. To pass the block on to another method or store it, capture it with &name:

Ruby Capturing a block with &

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

&transform turns the block into a Proc object; & in a call (map(&transform)) turns it back into a block. &:upcase converts a symbol into a block. Blocks have their own lesson (Blocks).

The full parameter order

When you combine kinds, Ruby requires this order:

  1. required positional (a, b)
  2. optional positional (c = 1)
  3. splat (*rest)
  4. required positional after the splat (z)
  5. keywords, required or optional (key:, opt: 2)
  6. double splat (**opts)
  7. block (&block)
Ruby Every kind at once

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

In the first call 1 is a, 9 is z (a required parameter after the optional one takes priority), and b falls back to its default. Method#parameters reports each parameter's kind (req, opt, rest, keyreq, key, keyrest, block), which is how libraries inspect your methods. Seven kinds in a single method is a design smell: use it for understanding, not as a pattern.

Argument forwarding

Sometimes a wrapper should pass everything to another method unchanged. Ruby has three levels of help.

The ... operator forwards positional arguments, keywords and the block:

Ruby Forwarding with ...

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Anonymous forwarding (Ruby 3.2 and later) lets you forward one kind without naming it, using bare *, ** and &:

Ruby Anonymous *, ** and & forwarding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Anonymous forwarding is ideal for thin wrappers, where inventing names such as args would only add noise. Use ... when you want to forward everything and do not need to touch any argument. If the wrapper must inspect or change one of them, name it and forward the rest explicitly.

Pitfalls worth knowing

  • Do not use a hash for options when keywords fit. def run(opts = {}) accepts misspelled keys silently.
  • A required parameter after optional ones changes how values are assigned, as in everything(1, 9, ...) above. Avoid it unless it reads naturally.
  • Keywords are not positional. Since Ruby 3.0, foo({a: 1}) and foo(a: 1) mean different things. Use ** to spread a hash.
  • nil is a value. connect(host: nil) passes nil; it does not use the default.
  • Arity matters for blocks and lambdas. Methods and lambdas are strict about the number of arguments; ordinary blocks and procs are lenient (Procs and Lambdas).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when you call def area(w, h) with area(3)?

    Ruby methods check the argument count strictly. A missing positional argument is never filled with nil.
  2. 2. In def connect(host:, port: 80), what does host: mean?

    A keyword followed by a colon and no default is required. Omitting it raises ArgumentError (missing keyword: :host).
  3. 3. How do you pass the hash opts = { host: "db" } as keyword arguments in Ruby 3+?

    The double splat spreads a hash into keywords. Since Ruby 3.0 a plain hash is a positional argument.
  4. 4. What is rest in def f(a, *rest) when called as f(1)?

    The splat parameter always receives an array; with no extra arguments it is empty.
  5. 5. Which definition forwards positional arguments, keywords and a block to another method?

    The ... operator forwards everything. The other options forward only one kind, or reference a variable that does not exist.

Summary

  • Parameters are positional (required, optional with =), a splat *rest, keywords (key: required, key: default optional), a double splat **opts and a block &blk, in that order.
  • Ruby checks argument counts and keyword names strictly and raises ArgumentError with a clear message.
  • Use keywords when a call has several parameters or unclear values; use **hash to spread a hash, and host:, port: shorthand for same-named variables.
  • Default values are evaluated on each call, so list = [] is safe.
  • Forward arguments with ... or the anonymous *, ** and &.
  • Method#parameters shows what a method accepts.

Next: Blocks