Ruby3.4 Makes "it" As Default Block Parameter

Ruby2.7 Introduced Numbered Parameters

Ruby introduced numbered parameters intended to simplify writing short blocks. Below are few example of numbered parameters.

["Ruby", "on", "Rails"].each { puts _1 }
# Ruby
# on
# Rails
# => ["Ruby", "on", "Rails"]

["Ruby", "on", "Rails"].each_with_index { puts _1, _2 }
# "Ruby"
# 0
# "on"
# 1
# "Rails"
# 2
# => ["Ruby", "on", "Rails"]

So we can see that the instead of using random parameter name we can use these numbered parameters.

But it is hard to remember the order of parameters, naming those parameters makes it easy to identify them because _1 or _2 is not immediately obvious.

This is only useful when block has single parameter.

But when there is singly block parameter and we use numbered parameter like _1, there is confusion, there might be a second argument also like _2, and we might waste time to think about _2, even if _2 doesn’t exist.

it as Default Block Parameter

To overcome this Ruby introduces it as a default block parameter.

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

its behavior should be as close to _1 as possible. it should treat array arguments in the same way as _1. it doesn’t work in a block when an ordinary parameter is defined.

And Ruby 3.3 Warns it method calls without a receiver, arguments, or a block.

def run(&block) = puts yield

def it = "str"

def method

  run { it }
end

method

# warning: `it` calls without arguments will refer to the first block param in Ruby 3.4; use it() or self.it

This feature can make code more concise and readable, especially in situations where the block’s argument is used directly and doesn’t need a specific name.

To know more about this please go through this issue

Need help on your Ruby on Rails or React project?

Join Our Newsletter