Ruby’s Enumerable module is beautiful. Coming from a more procedural programming background, it can take some time to fully appreciate that beauty. One pattern I see new Rubyists repeating relates to transforming data structures. This is an easy problem for a proceduralist:
1 2 3 4 5 6 7 8 9 10
This works, but it’s not beautiful. It’s even worse if the proceduralist loops over the data to transform. Once the proceduralist embraces Ruby, and studies the Enumerable module, they learn of the #each_with_object method. This method allows us to simplify our code:
1 2 3 4 5
Enumerable#each_with_object allows us to declare the new data structure as a parameter, reference it in our block, and then returns it for us; all in one method call. For simple operations, this can often be a one-liner:
1 2 3
This is beautiful. Any time you find yourself instantiating a new data structure and then filling it, consider using #each_with_object.