Simplify your Ruby code with tap
I only recently discovered the tap method, which was added in Ruby 1.9. Basically, if you ever find yourself writing code like this:
You can now simplify this code using the tap method:
Basically tap allows us to access any variable in a block, which then returns the original variable.
Another nice use case is when initializing a new object:
This saves us having to first assign the object of interest to a local variable simply to be able to reference it.
The implementation for tap looks something like this:
Which means it’s available on any object. Happy coding.