No need to try

I previously talked about our try method as an easy way of dealing with exceptions inside expressions:

puts try {patient.name.first_name} || "-- no name --"

Otherwise, you would have to set up your own begin / rescue / end blocks:

puts begin
  patient.name.first_name
rescue
  "-- no name --"
end

which would have been too ugly for our modern sentitivities.

I was wrong. I should have known it.

It turns out that ruby lets you use rescue without a begin. This is most commonly seen in exception handling for methods:

def my_method
  # do something
rescue
  # handle exception
end

It also turns out the ruby lets you use rescue as a postfix modifier for an expression, just like all those if and unless. So you can write something like:

puts patient.name.first_name rescue puts "-- no name --"

And it also happens that “inline rescues” work inside parenthesis. So you can do something like:

puts (patient.name.first_name rescue "-- no name --")

Which is exactly the use-case for our original try method.

So now that I had a piece of code blessed by _why, I’ll have to get rid of it or risk not beeing rubyish enough. You live and you learn.

One Response to “No need to try”

  1. NP Says:

    You’ve made my day.

Leave a Reply