Ruby 2.7 — Numbered Parameters

The Short Version

[1, 2, 3].map { _1 + 3 }
=> [4, 5, 6]

The Discussion

Examples

Valid Only In Blocks

assert_syntax_error('_1', /outside block/)
assert_valid_syntax('proc {_1}')
proc { _1 }
=> #<Proc:0x0000000111d42990@(pry):6>
_1
SyntaxError: (eval):2: numbered parameter outside block

Naming Rules

assert_syntax_error('proc {_01}', /leading zero/)    assert_syntax_error('proc {_1_}', /unexpected/)
(1..1_000_000).each_slice(1_000).map { _1 + _1_000 + _2 + _3 }
SyntaxError: unexpected local variable or method, expecting '}'
..._slice(1_000).map { _1 + _1_000 + _2 + _3 }
... ^~~~
(eval):2: numbered parameter outside block
...e(1_000).map { _1 + _1_000 + _2 + _3 }
...

Multiple Numbered Parameters

assert_equal(3, eval('[1,2].then {_1+_2}'))
assert_equal("12", eval('[1,2].then {"#_1#_2"}'))
{name: 'foo', age: 42}.map { [_1, _2] }
=> [[:name, "foo"], [:age, 42]]
(1..9).each_slice(3).map { _1 + _2 + _3 }
=> [6, 15, 24]

Too Large of a Number

assert_syntax_error('proc {_9999999999999999}', /too large/)
#define NUMPARAM_MAX 100 /* INT_MAX */
[13] pry(main)> (1..1_000_000).each_slice(1_000).map { _101 }
[13] pry(main)*

Ordinary Parameters

assert_syntax_error('proc {|| _1}', /ordinary parameter is defined/)    assert_syntax_error('proc {|x| _1}', /ordinary parameter is defined/)

Hashes and Objects

[{name: 'foo'}, {name: 'bar'}].map { _1[:name] }
=> ["foo", "bar"]
[{name: 'foo'}, {name: 'bar'}]
.map { OpenStruct.new(_1) }
.map { _1.name }
=> ["foo", "bar"]

Wrapping Up

--

--

--

Find new posts on dev.to: https://dev.to/baweaver

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Digital Twins, Model-Based Definition and more

GE Digital Thread

What is Serverless Computing? Server-less Computing in Simple English

Top 5 Skills Every Tester Should Master

How Much Does It Cost to Create a Taxi App?

App Localization in Swift — iOS Swift Guide

ACID Properties

String formatting

How to bring the most value as a junior developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Brandon Weaver

Brandon Weaver

Find new posts on dev.to: https://dev.to/baweaver

More from Medium

The performance of .to_json in Rails sucks and there’s nothing you can do about it

Ruby Opportunities in the Current Programming Landscape

Advanced Active Recored Query with Arel

Let’s Start Rebuilding rails