Anonymous block argument in Ruby

Anonymous block argument in Ruby

In the Ruby programming language, it is possible to use default block parameters instead of variables. This feature allows for more concise and expressive code.

Before Ruby 2.7 #

We would need to write code like this:

irb(main):005> [1, 2, 3].map { |el| el }
=> [1, 2, 3]

From Ruby 2.7 #

However, in Ruby 2.7, numbered parameters were introduced, which allows us to write code like this:

irb(main):010> [10, 100, 1000].each_with_index { p "#{_1}, #{_2}" }
"10, 0"
"100, 1"
"1000, 2"

In the above example, _1 refers to the first element of the array, and _2 refers to its index.

From Ruby 3.4 #

In the newer version of Ruby 3.4, anonymous block arguments were added, and now we can refer to the first element using the word it. For example:

irb(main):012> [1, 2, 3].each { it }
=> [1, 2, 3]

In this case, it refers to the current element being iterated over.

These features provide more flexibility and readability when working with blocks in Ruby. They allow for more concise code and reduce the need for explicit variable declarations.

Reading this because something is going wrong?

A free code audit gives you a written assessment of your codebase in plain English.

Get a Free Code Audit

Rated 4.8/5 on Clutch · you keep the write-up either way

Comments