Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 134 ยท Methods and Blocks

Endless Methods and Modern Syntax

Modern Ruby syntax explained - endless methods, the it block parameter, numbered parameters, hash shorthand like {x:, y:}, and anonymous argument forwarding.

Ruby changes slowly but steadily, and each release since 3.0 has trimmed some ceremony from everyday code. A one-line method no longer needs end. A block that takes one argument no longer needs a name for it. A hash built from local variables no longer repeats each name twice. Methods that pass their arguments on to another method no longer need to name them at all.

None of these features lets you do something you could not do before; they let you say it with less noise. This lesson collects five of them: endless methods, the it block parameter, numbered parameters (_1, _2), hash shorthand, and anonymous argument forwarding. For each one you will see the idea, the rules, the error you get when you break the rules, and a judgment about when the short form reads better than the long one.

Endless methods

An endless method defines a method with = instead of end. The body is a single expression, and its value is the return value (as always in Ruby).

Ruby Endless method definitions

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 definition def square(x) = x * x is exactly the same as the three-line version. Parameters work as in any method (defaults, keywords, splats). Methods with no parameters need no parentheses, as in def banner = .... The endless form shines for small query methods and simple delegators: things that compute and return one value.

Rules and limits

  • The body is one expression. For several steps, use a normal def ... end.
  • A setter cannot be endless. def x=(v) = @x = v is a syntax error with the message invalid method name; a setter method cannot be defined in an endless method definition.
  • A call with arguments but without parentheses is allowed in the body since Ruby 3.3 (def log(msg) = puts "[log] #{msg}"), but parentheses are clearer.
  • private def helper = 42 works, because def returns the method name as a symbol and private accepts it.
  • A rescue modifier applies to the body: def risky(n) = Integer(n) rescue -1.
Ruby Endless methods with private and rescue

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.

Use endless methods when the whole definition fits comfortably on one line and reads like a formula. If you find yourself adding a ; or wrapping the right-hand side in a long chain, switch back to def ... end. Short is a goal, not a rule.

The it parameter (Ruby 3.4)

Most blocks take one argument, and most of the time its name carries little information: users.map { |user| user.name }. Ruby 3.4 lets you write it instead.

Ruby it as the implicit block parameter

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.

it always means "the first (and only) argument of the innermost block". Notice the nested blocks in the last line: each it belongs to its own block, so the inner one does not clash with the outer one.

Some details worth knowing:

  • Outside a block, it is not magic. Using it where no block provides it gives NameError: undefined local variable or method 'it' for main.
  • If a local variable named it exists, the variable wins. That is a classic trap in old code.
  • When the block receives an array as its single argument, it is that whole array. It does not destructure.
Ruby it is a plain parameter, and a local variable named it wins

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.

After it = 10, the block { it } ignores its argument and returns 10 each time. In the last expression, the then block's it is also the local 10, and calling sum on an Integer fails with undefined method 'sum' for an instance of Integer. Do not name your own variables it.

Numbered parameters: _1, _2

Before it there were numbered parameters: _1 is the first block argument, _2 the second, and so on. They are handy when a block receives two values.

Ruby Numbered 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.

When you use _1 and _2, an array argument is split into its parts like |a, b|. With only _1, the block receives the whole element: [[1, 2]].map { _1 } returns [[1, 2]], the same as it.

Numbered parameters and it cannot be mixed in the same block. Ruby refuses to run the program:

Ruby Mixing it and _1 (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.

You get a SyntaxError containing numbered parameters are not allowed when 'it' is already used. In new code prefer it for one argument and named parameters (|name, age|) for two or more. Numbered parameters are fine for quick two-argument blocks, but readers have to remember what _2 means.

Hash shorthand: {x:, y:}

Code that builds hashes from local variables often repeats names: { name: name, age: age }. Since Ruby 3.1 you can leave out the value when it has the same name as a variable or method in scope.

Ruby Hash shorthand

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.

{ x:, y: } is { x: x, y: y }. The shorthand also works when passing keyword arguments (make_user(name:, age:)). If no variable or method with that name exists, Ruby raises the usual error: undefined method 'country' for main. The shorthand is a good fit for returning a "bag of values" from a method and for forwarding variables with the same names as parameters. It is a poor fit when the variable name does not describe the key.

A shorthand argument at the end of a line in a call without parentheses swallows the next line. With x = 1 and y = 2, the three lines puts x:, then y on the next line, run as puts(x: y) and print {x: 2}, not {x: 1}. Use parentheses when you write key: as the last thing on a line.

Anonymous argument forwarding

A method that just passes its arguments to another method used to need names for all of them. Modern Ruby has four ways to forward without naming.

Ruby Anonymous forwarding with *, **, & and ...

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.

  • * forwards all positional arguments, ** all keyword arguments, & the block.
  • ... forwards all three at once. It can follow leading parameters, as in log_call(name, ...), which lets a wrapper take its own arguments and pass the rest on.

This is the idiomatic way to write decorators and delegators: the wrapper does not need to know how many arguments the target takes, what they are called, or whether a block is given. Compare the old way, def wrap(*args, **kwargs, &block) = target(*args, **kwargs, &block), with def wrap(...) = target(...).

Forwarding also works inside a block in the same method (def f(*) = [1].each { g(*) }). A named parameter is always allowed.

Putting it together

Ruby A small report builder in modern Ruby

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.

Count the ceremony that is missing: no end for the small helpers, no |sale| for one-argument blocks, no grand_total: grand_total in the result, and no argument list in the forwarding wrapper. The code is shorter and, because the pieces are small, easier to scan.

When to use the short forms

Prefer them when they make the code shorter and no less clear: single-expression helpers, one-argument blocks, hashes of well-named locals, and thin wrappers. Fall back to the long forms when a method does several things, when a block needs more than one argument (name them), when the blocks are deeply nested, or when your team runs Ruby versions older than 3.4. The it parameter needs 3.4, endless methods need 3.0, hash shorthand 3.1, anonymous & forwarding 3.1 and anonymous * and ** forwarding 3.2.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which is a valid endless method?

    def name(args) = expression defines an endless method. Setters cannot be written this way, and the form has no end keyword.
  2. 2. What does [[1, 2], [3, 4]].map { it } return?

    it is the whole block argument. It does not destructure the pair, so each element is returned unchanged.
  3. 3. What happens if a local variable named it exists and you write [1, 2].map { it }?

    A local variable named it takes priority over the implicit block parameter, which is why you should never name a variable it.
  4. 4. What is { x:, y: } equivalent to?

    The value is omitted, and Ruby looks up a local variable or method with the same name as the key.
  5. 5. Which signature forwards positional arguments, keyword arguments and the block to another method?

    ... forwards everything. * forwards only positional arguments, ** only keywords and & only the block.

Summary

  • def name(args) = expression defines a method in one line; setters cannot be endless.
  • it (Ruby 3.4) is the implicit single block parameter; it does not destructure, and a local variable called it takes precedence.
  • _1, _2 are numbered parameters; they split array arguments, and cannot be combined with it.
  • { x:, y: } and call(x:, y:) take the values from variables or methods of the same name.
  • *, **, & and ... forward arguments without naming them; ... forwards all three.
  • Use the short forms when they stay readable, and check your Ruby version first.

Next: Arrays