Posts Tagged: ruby

Text

Great little trick by Peter Cooper (@peterc).

You can use j and jj just as p and pp to print an object as json:

  require 'json'
  data = { name: "Max Mustermann", tags: ['some', 'tags']}
  j data # for simple output
  jj data # for really beautiful output

If you wanna learn a few more tricks, visit his ruby trick shots video.

Text

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.