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

Scaling the Docker container using Kubernetes: AI End-to-End Series (Part — 7)

#100DaysOfCode — N-Queen Challenge

How to resolve Deploy App Engine get Error Response: [4] DEADLINE_EXCEEDED

Why we are not cross-platform developers

Things to know before building microservices.

SetUp Couchbase through Command Line

Why learning from Documentation is better than watching YouTube Tutorial ?

Reading Between the Lines: My Hackbright Project Blog

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

Creating your own backend using Ruby and Active Record

Seeding Data with Faker in Ruby

The logo for the Faker library

Send emails on Rails using SendGrid