it ブロックパラメータ

Ruby 3.4 で “a block parameter with no variable name” が追加された。

it is added to reference a block parameter with no variable name. [Feature #18980]

ary = ["foo", "bar", "baz"]

p ary.map { it.upcase } #=> ["FOO", "BAR", "BAZ"]

ref. Ruby 3.4.0 Released | Ruby

ブロックパラメータ名を意識せず、it で参照できて便利。

使ってみる

> RUBY_VERSION
=> "3.4.5"

> (1..10).map { it ** 2 }
=> [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Ruby 3.3 の場合

下記の通りエラーとなる。

> RUBY_VERSION
=> "3.3.9"

> (1..10).map { it ** 2 }
(irb):3: warning: `it` calls without arguments will refer to the first block param in Ruby 3.4; use it() or self.it
(none):1: warning: `it` calls without arguments will refer to the first block param in Ruby 3.4; use it() or self.it
(irb):3:in `block in <top (required)>': undefined local variable or method `it' for main (NameError)

(1..10).map { it ** 2 }
              ^^
	from (irb):3:in `each'
	from (irb):3:in `map'
	from (irb):3:in `<main>'
	from <internal:kernel>:187:in `loop'

参考

関連記事