Very often in Ruby (and Rails specifically) you have to check if something exists and then perform an action on it, for example:
if @objects.any?
puts "We have these objects:"
@objects.each { |o| puts "hello: #{o}"
end
This is as short as it gets and all is good, but what if you have @objects.some_association.something.hit_database.process instead of @objects? I would have to repeat it second time inside the if expression and what if I don’t know the implementation details and the method calls are expensive?
The obvious choice is to create a variable and then test it and then process it, but then you have to come up with a variable name (ugh) and it will also hang around in memory until the end of the scope.
Why not something like this:
@objects.some_association.something.hit_database.process.with :any? do |objects|
puts "We have these objects:"
objects.each { ... }
end
How would you do this?
What about tap?