DEV Community

Cover image for Anonymous block argument in Ruby
JetThoughts Dev for JetThoughts

Posted on • Edited on • Originally published at jetthoughts.com

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]
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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.


Paul Keen is an Open Source Contributor and a Chief Technology Officer at JetThoughts. Follow him on LinkedIn or GitHub.

If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories.

Top comments (0)