I just finished coding my loop when it struck me and I searched for a solution which feels more ruby like.

What I was trying to achieve is executing a piece of code until it ran without an exception. This might sound stupid, but in some cases it makes perfect sense. In this specific case, I was fetching secure data from an external provider via SSL connection. Unfortunately, the SSL connection did not always open as expected. So I have to try till it works (or I give up).

Instead of using a loop, ruby provides us with keyword retry - What a wonderful little keyword:

begin
  # Put your code here which has to be executed
rescue YourExpectedException => ex
  retry
end

And if you wanna protect yourself from an endless loop, add something like retry unless i > 10.

  1. namxam posted this