Anonymous block parameter in Ruby

August 31, 2024

Recently, I learned about numbered parameters in Ruby, which simplify block parameters by eliminating the need to explicitly name each one. I then explored this further and discovered an even more flexible approach: using it keyword as an anonymous block parameter. In this blog post, we'll briefly discuss about these Ruby features!

A brief history

Before Ruby 2.7, working with blocks in Ruby required explicitly naming each parameter, which could make the code more verbose and harder to read. For example:

[1, 2, 3].map { |element| element * 2 }
# => [2, 4, 6]

To simplify this, Ruby 2.7 introduced numbered parameters (you can see the proposal here):

[10, 100, 1000].each_with_index { p "#{_1}, #{_2}" }
# => "10, 0"
# => "100, 1"
# => "1000, 2"

Here, _1 refers to the first element, while _2 refers to the index. This approach makes the code cleaner and more focused on the block’s logic. However, it can still be somewhat confusing and may not always be as readable as desired.

The proposal: introducing it

Recognizing the limitations of numbered parameters, a proposal for Ruby 3.4 (you can see it here) suggested introducing it as an anonymous block parameter. The aim was to simplify block syntax even further by replacing numbered placeholders with the more intuitive it keyword:

[10, 20, 30].select { it > 15 }
# => [20, 30]

In this example, it represents the current element being processed, serving as an anonymous parameter. This enhancement aims to simplify code, making it more readable and expressive by eliminating the need to remember parameter numbers.

Conclusion

In summary, both numbered parameters and the anonymous parameter enhance how we handle block parameters in Ruby. Numbered parameters offer a concise way to reference multiple parameters, but they can sometimes be confusing, especially with several parameters. On the other hand, the it keyword acts as an anonymous parameter, simplifying code when you only need to work with a single parameter.

The key takeaway is to use these approaches to simplify your code blocks, but only if they don't reduce readability. Shorter code isn't always easier to read; it's important to balance between being concise and being clear. Always consider how these features affect the overall readability of your code to make the best decision.

I hope you found this blog post useful. Thanks for reading!

puts "Ah shit, here we go again."

Profile picture

Written by Mateus Elias using Gatsby, to share tech knowledge and personal experiences! You should follow him on GitHub.