Block parameters: `it` and numbered parameters
suggest changeMost blocks are tiny: { |user| user.name }, { |n| n * 2 }. Naming the parameter in a one-liner like that is mostly noise, because the name appears twice in a dozen characters. Ruby has two ways to refer to block parameters without declaring them:
- numbered parameters
_1,_2, ..._9, added in Ruby 2.7 it, added in Ruby 3.4, which stands for the first (and usually only) parameter
This article explains how both work, how they differ when a block receives several values, the nesting rules, how they affect a lambda's arity, and when to use them instead of a named parameter or &:symbol. All examples were run with Ruby 4.0 and RuboCop 1.92.
it: the implicit parameter
Inside a block that declares no parameters, it refers to the first argument the block was called with:
words = %w[ruby is fun]
p words.map { |word| word.upcase } # named parameter
p words.map { it.upcase } # it (Ruby 3.4+)
p words.map { _1.upcase } # numbered parameter (Ruby 2.7+)
p [3, 1, 2].sort_by { -it }
p (1..10).select { it.even? }
words.each do
puts "#{it} has #{it.size} letters"
end
["RUBY", "IS", "FUN"]
["RUBY", "IS", "FUN"]
["RUBY", "IS", "FUN"]
[3, 2, 1]
[2, 4, 6, 8, 10]
ruby has 4 letters
is has 2 letters
fun has 3 letters
it reads like English: "select it if it is even". It works with { } and do ... end blocks, in -> { } lambdas, in proc { } and in define_method.
Before 3.4, a bare it inside a block was a call to a method named it. Ruby 3.3 printed a deprecation warning for such calls, and 3.4 made the switch. Code that needs to run on Ruby 3.3 or older has to use _1 or a named parameter.
Numbered parameters _1 to _9
_1 is the first parameter, _2 the second, and so on up to _9. They are handy when a block receives several values:
langs = %w[ruby go rust]
p langs.each_with_index.map { "#{_2}: #{_1}" }
p langs.each_with_index.map { it }
p langs.each_with_object({}) { _2[_1] = _1.size }
p (1..6).each_slice(2).map { _1 * _2 }
p langs.zip([1995, 2009, 2010]).to_h { [_1.to_sym, _2] }
["0: ruby", "1: go", "2: rust"]
["ruby", "go", "rust"]
{"ruby" => 4, "go" => 2, "rust" => 4}
[2, 12, 30]
{ruby: 1995, go: 2009, rust: 2010}
Note the second line: each_with_index yields two values, and it only sees the first one.
_0 and _10 are not numbered parameters. They are ordinary identifiers, so using them in a block raises NameError: undefined local variable or method '_0'.
You can't assign to a numbered parameter, or use one as a local variable name anywhere:
_1 = "nope"
e5.rb:1: syntax error found (SyntaxError)
> 1 | _1 = "nope"
| ^~ _1 is reserved for numbered parameters
it vs _1 when an element is an array
The most important difference between the two forms is how they treat a single array argument.
A block declared as { |x| ... } gets the whole array, while { |a, b| ... } destructures it into its elements. Implicit parameters follow the same rule, and the rule is decided by the highest numbered parameter used in the block:
itbehaves like|x|: it's always the whole value_1used alone also behaves like|x|- once the block uses
_2(or higher), it behaves like|a, b|, and_1becomes the first element
pairs = [[1, 2], [3, 4]]
p pairs.map { it } # it is the whole element
p pairs.map { _1 } # _1 alone also is the whole element
p pairs.map { _1 + _2 } # using _2 makes the block destructure
p pairs.map { _2 } # _2 alone works too
# equivalent named blocks
p pairs.map { |pair| pair }
p pairs.map { |a, b| a + b }
[[1, 2], [3, 4]]
[[1, 2], [3, 4]]
[3, 7]
[2, 4]
[[1, 2], [3, 4]]
[3, 7]
So { _1 } and { _1 + _2 } give _1 two different meanings. That surprises people, and it's one reason it was added: it never changes meaning. Use it for one value and _1/_2 only when you need several.
Hash methods that yield two values
Hash iteration has a related trap. Some Hash methods yield one [key, value] array, and some yield the key and the value as two separate arguments. it and _1 see different things depending on which kind of method it is:
stock = {apples: 5, pears: 0, plums: 12}
stock.each { p it; break } # each yields one [key, value] pair
stock.map { p it; break }
stock.select { p it; break } # select yields key and value separately
stock.select { p _1; break }
p stock.select { _2 > 0 } # fine: _2 is the value
p stock.select { |_k, v| v > 0 }
p stock.select { it[1] > 0 } # bug: it is the key, :apples[1] is "p"
[:apples, 5]
[:apples, 5]
:apples
:apples
{apples: 5, plums: 12}
{apples: 5, plums: 12}
s4.rb:10:in 'Comparable#>': comparison of String with 0 failed (ArgumentError)
p stock.select { it[1] > 0 } # bug: it is the key, :apples[1] is "p"
^
from s4.rb:10:in 'block in <main>'
from s4.rb:10:in 'Hash#select'
from s4.rb:10:in '<main>'
In Ruby 4.0, each, map, filter_map, count, find, any?, min_by, sum and the other Enumerable methods give it the pair. Hash's own filtering methods, select/filter, reject, select!/filter!, reject!, delete_if, keep_if, and also to_h with a block, yield two values, so it is just the key. When a hash block needs both key and value, use _1 and _2 or, better, name them: { |name, count| ... }.
Nesting
Every block gets its own it. In a nested block, it refers to the innermost block's parameter, and the outer value is shadowed:
p [[1, 2], [3]].map { it.map { it * 10 } } # inner it shadows outer it
p [[1, 2], [3]].map { |row| row.map { row.size * it } }
[[1, 2]].each { p it; it.each { p _1 } } # it outside, _1 inside: OK
[[10, 20], [30]]
[[2, 4], [3]]
[1, 2]
1
2
If the inner block needs the outer value, give the outer block a named parameter, as in the second line.
Numbered parameters are stricter. A block can't use _1 if an enclosing or nested block also uses numbered parameters, because it would be unclear which block _1 belongs to. Both directions are compile-time errors:
[[1, 2]].each { _1.each { p _1 } }
e1.rb:1: syntax error found (SyntaxError)
> 1 | [[1, 2]].each { _1.each { p _1 } }
| ^~ numbered parameter is already used in outer block
[1].each { [2].each { p _1 }; p _1 }
e2.rb:1: syntax error found (SyntaxError)
> 1 | ... _1 }
| ^~ numbered parameter is already used in inner block
What can't be mixed
A block uses exactly one style. Mixing an ordinary parameter with _1, or _1 with it, is a syntax error:
[1, 2].each { |x| p _1 }
e3.rb:1: syntax error found (SyntaxError)
> 1 | [1, 2].each { |x| p _1 }
| ^~ numbered parameters are not allowed when an ordinary parameter is defined
[1, 2].each { p _1 + it }
e4.rb:1: syntax error found (SyntaxError)
> 1 | [1, 2].each { p _1 + it }
| ^~ 'it' is not allowed when a numbered parameter is already used
Because these are syntax errors, they show up when the file loads, not when the block runs.
it is not a keyword
_1 is reserved, but it isn't. To stay compatible with existing code (RSpec's it "does something" do, local variables named it), Ruby treats it as the block parameter only when nothing else claims the name. Three rules follow from that.
A local variable named it wins. If it is already a local variable in the surrounding scope, a block sees that variable:
it = "outer"
[1, 2].each { p it } # the local variable wins over the block parameter
"outer"
"outer"
Assigning to it creates a local variable. As with x = x, the variable exists (as nil) from the moment the parser sees the assignment, including on its right-hand side:
[3].each do
it = it * 100 # it on the right is still the block parameter
p it
end
s6c.rb:2:in 'block in <main>': undefined method '*' for nil (NoMethodError)
it = it * 100 # it on the right is still the block parameter
^
from s6c.rb:1:in 'Array#each'
from s6c.rb:1:in '<main>'
The comment in the code is what most readers expect, and it's wrong. Never assign to it: use a new name (total = it * 100). RuboCop's Style/ItAssignment cop flags it.
it with arguments is a method call. it "...", it("...") and it do ... end call a method named it. Only a bare it with no arguments, no parentheses and no receiver is the block parameter. Outside a block, a bare it is a normal method call:
def it(description) = puts("example: #{description}")
[42].each do
it "with an argument it is a method call"
p it # without arguments it is the block parameter
end
def answer = it
answer
example: with an argument it is a method call
42
s7.rb:1:in 'Object#it': wrong number of arguments (given 0, expected 1) (ArgumentError)
caller: s7.rb:8
| def answer = it
^^
callee: s7.rb:1
| def it(description) = puts("example: #{description}")
^^
from s7.rb:8:in 'Object#answer'
from s7.rb:9:in '<main>'
That's why RSpec specs keep working on Ruby 3.4+: it "adds numbers" do ... end passes an argument.
it also isn't a real local variable, so binding.local_variables doesn't list it and eval("it") inside a block raises NameError.
Lambdas and procs: arity and parameters
Implicit parameters change the arity of a lambda or proc exactly as the equivalent named parameters would. The highest numbered parameter used decides the count:
l_it = -> { it * 2 }
l_one = -> { _1 * 2 }
l_two = -> { _1 + _2 }
p [l_it.arity, l_one.arity, l_two.arity]
p l_it.parameters, l_two.parameters
p l_two.(2, 3)
begin
l_two.(2)
rescue ArgumentError => e
puts "ArgumentError: #{e.message}"
end
pr_it = proc { it }
pr_two = proc { [_1, _2] }
p [pr_it.arity, pr_two.arity]
p pr_it.parameters, pr_two.parameters
p pr_two.call(1) # missing arguments become nil
p pr_two.call([1, 2]) # a single array is splatted
p pr_it.call([1, 2]) # it is never splatted
p proc { _3 }.arity
[1, 1, 2]
[[:req]]
[[:req, :_1], [:req, :_2]]
5
ArgumentError: wrong number of arguments (given 1, expected 2)
[1, 2]
[[:opt]]
[[:opt, :_1], [:opt, :_2]]
[1, nil]
[1, 2]
[1, 2]
3
Things to notice:
-> { _1 + _2 }is a strict lambda taking exactly two arguments, the same as->(a, b) { a + b }.proc { _3 }has arity 3 even though it never touches_1or_2.parametersreports numbered parameters by name (:_1,:_2), butitshows up as an anonymous parameter ([[:req]]or[[:opt]]). Code that inspectsparametersto name things (some DSLs and dependency-injection helpers do) should not rely on a name forit.
The same holds for define_method, so this defines a method that takes one argument:
class Temperature
define_method(:to_f) { it * 9.0 / 5 + 32 }
end
p Temperature.instance_method(:to_f).arity
p Temperature.new.to_f(100)
1
212.0
Comparing with &:symbol
When a block only calls one method with no arguments on its parameter, &:symbol (see Converting to Proc) is still the shortest and most common form. it covers everything &:symbol can't: arguments, operators, indexing, string interpolation.
names = %w[ada grace linus]
p names.map(&:capitalize)
p names.map { it.capitalize }
p names.map { it[0] }
p names.map { "#{it}!" }
p names.map { it.center(9, "*") }
p names.select { it.size > 3 }.map(&:upcase)
["Ada", "Grace", "Linus"]
["Ada", "Grace", "Linus"]
["a", "g", "l"]
["ada!", "grace!", "linus!"]
["***ada***", "**grace**", "**linus**"]
["GRACE", "LINUS"]
The first two lines do the same thing. Most style guides, including RuboCop's Style/SymbolProc cop, still prefer map(&:capitalize) there. RuboCop 1.92 flags { |n| n.capitalize } and { _1.capitalize } but leaves { it.capitalize } alone, so either form passes. The rest of the lines can't be written with &:symbol at all.
Style guidance
The community consensus, also written down in the coding conventions article, is:
- Use
itin short, single-line blocks with one parameter, when the meaning is obvious from the method name:users.map { it.email },lines.reject { it.strip.empty? }. - Prefer
itover_1for a single parameter on Ruby 3.4+._1only exists in new code when it has to run on Ruby 2.7 to 3.3. - Use a named parameter in multi-line blocks, and whenever a name explains something:
orders.each { |order| ... }reads better thanitsix lines down. - Avoid
_2and higher in most code.{ "#{_2}: #{_1}" }is short but forces the reader to remember which is which.{ |name, index| "#{index}: #{name}" }doesn't. For a quickeach_slice(2).map { _1 * _2 }it's fine. - Name the parameter in hash blocks to avoid the "is
itthe pair or the key?" question. - Never assign to
it, and don't useitas a local variable name in new code.
RuboCop has three cops for this. They are "pending" in 1.92, so they run only with NewCops: enable or when you enable them explicitly:
Style/ItBlockParameter: default styleallow_single_linereplaces_1withitin single-line blocks and flagsitin multi-line blocks. Other styles areonly_numbered_parameters,always(also suggestsitinstead of|x|) anddisallow.Style/NumberedParameters:allow_single_line(default) ordisallow.Style/NumberedParametersLimit: the maximum count of numbered parameters in one block,Max: 1by default, so_1with_2is reported.
With this .rubocop.yml:
AllCops:
NewCops: enable
TargetRubyVersion: 4.0
SuggestExtensions: false
Style/ItBlockParameter:
EnforcedStyle: allow_single_line
and this file:
# frozen_string_literal: true
prices = [12, 7, 30]
puts prices.map { _1 * 2 }.inspect
puts prices.select { |price| price > 10 }.inspect
puts prices.sum { it * 2 }
prices.each do
tax = it * 0.2
puts tax
end
RuboCop reports:
$ rubocop --only Style/ItBlockParameter,Style/NumberedParameters,Style/NumberedParametersLimit orders.rb
Inspecting 1 file
C
Offenses:
orders.rb:4:19: C: [Correctable] Style/ItBlockParameter: Use it block parameter.
puts prices.map { _1 * 2 }.inspect
^^
orders.rb:7:1: C: Style/ItBlockParameter: Avoid using it block parameter for multi-line blocks.
prices.each do ...
^^^^^^^^^^^^^^
1 file inspected, 2 offenses detected, 1 offense autocorrectable
rubocop -A rewrites { _1 * 2 } to { it * 2 }. The multi-line block has to be fixed by hand, by giving it a name like |price|.
Summary
it |
_1 alone |
_1, _2, ... |
|
|---|---|---|---|
| Available since | Ruby 3.4 | Ruby 2.7 | Ruby 2.7 |
| Behaves like | one named parameter | one named parameter | several named parameters (destructures arrays) |
| Lambda arity | 1 | 1 | highest number used |
| Nested blocks | allowed, inner shadows outer | not if another level uses numbered params | same as _1 |
| Reserved name | no (local variable or method call wins) | yes | yes |
| Mix with named parameters or each other | no | no | no |
Use it for one obvious value in a one-liner, &:symbol when it's a single method call, and a named parameter for everything else.