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
It is as short as everything and everything is fine, but what if you have @objects.some_association.something.hit_database.process instead of @objects ? I would have to repeat it a second time inside the if , and what if I don't know the implementation details and 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 the variable name (ugh) and it will also be in memory until the end of the area.
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 do you do this?
source share