Use block for loop in Ruby
When we have a block of code that we'd like to loop through given numbers of times, we typically do
(1..10).each
# Run some code
end
Sometimes it's hard to document where the number 10 comes from and why. You certainly can do something like this:
ENV['QUERY_RETRY_LIMI'].to_i.times do
# Run some code
end
That's kind of explaining where the number is from. But next time you run a similar loop, you'll have to do the same thing agin.
A better way of doing this is to use block.
def with_query_try_limit(limit:
ENV['QUERY_RETRY_LIMIT'].to_i)
limit.times do
yield
end
end
So whenever there's a need to loop through a function ENV['QUERY_RETRY_LIMIT']
numbers of times, it could be referenced as:
with_query_try_limit do
# Code
end
It makes a better self documenting as well as be reusable.