JT Book a call

Blog

Anonymous block argument in Ruby

Published

1 min read

Anonymous block argument in Ruby
In this post

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.

Read next

Tell us whatyou need built

JetThoughts has been building software since 2008. Book a call, or write to sales@jetthoughts.com. You'll leave the call with a written one-page scope within 2 working days.

#01 Paul Keen
Paul KeenFounder

A 30-minute call; pick a time.