Misc #15723


Reconsider numbered parameters

Added by sos4nt (Stefan Schüßler) about 2 years ago. Updated over 1 year ago.



I just learned that numbered parameters have been merged into Ruby 2.7.0dev.

For readers not familiar with this feature: it allows you to reference block arguments solely by their index, e.g.

[1, 2, 3].each { |i| puts i }

# can become

[1, 2, 3].each { puts @1 }

I have an issue with this new feature: I think it encourages sloppy programming and results in hard to read code.

The original proposal was to include a special variable (or keyword) with a readable name, something like:

[1, 2, 3].each { puts it }

# or

[1, 2, 3].each { puts this }

Granted, that looks quite lovely and it actually speaks to me – I can understand the code. And it fits Ruby: (quoting the website)

[Ruby] has an elegant syntax that is natural to read and easy to write.

But the proposed it / this has limited application. It's only useful when dealing with a single argument. You can't have multiple it-s or this-es. That's why @1, @2, @3 etc. were chosen instead.

However, limiting the usefulness to a single argument isn't bad at at. In fact, a single argument seem to be the limit of what makes sense:

h = { |hash, key| hash[key] = "Go Fish: #{key}" }

# vs

h = { @1[@2] = "Go Fish: #{@2}" }

Who wants to read the latter? That looks like an archaic bash program (no offense). We already discourage Perl style $-references: (from The Ruby Style Guide)

Don't use the cryptic Perl-legacy variables denoting last regexp group matches ($1, $2, etc). Use Regexp.last_match(n) instead.

I don't see how our code can benefit from adding @1 and @2.

Naming a parameter isn't useless – it gives context. With more than one parameter, naming is crucial. And yes, naming is hard. But avoiding proper naming by using indices is the wrong way.

So please reconsider numbered parameters.

Use a readable named variable (or keyword) to refer to the first argument or ditch the feature entirely.


implicit-param.diff (20 KB) implicit-param.diff jeremyevans0 (Jeremy Evans), 04/24/2019 05:42 AM

Related issues

Related to Ruby master - Feature #4475: default variable name for parameterClosednobu (Nobuyoshi Nakada)Actions
Related to Ruby master - Bug #15708: Implicit numbered argument decomposes an arrayRejectedmatz (Yukihiro Matsumoto)Actions
Related to Ruby master - Feature #15897: `it` as a default block parameterClosedmatz (Yukihiro Matsumoto)Actions
Related to Ruby master - Bug #16178: Numbered parameters: _1 should be the same as |x| and _0 should not existClosedmatz (Yukihiro Matsumoto)Actions

Also available in: Atom PDF