Tip: Rescue blocks in Ruby

Everybody must have heard and used the exception handling in Ruby. But here is one trick that might be useful. "Rescue blocks don't need to be tied to a 'begin' "

def x
  begin
    # ...
  rescue
    # ...
  end
end

def x
  # ...
rescue
  # ...
end

You can also use rescue in its single line form to return a value when other things produces error.

data = { :age => 10 }
h[:name].downcase                         # ERROR
h[:name].downcase rescue "No name"        # => "No name"

Comments

Popular posts from this blog

Inserting and Moving elements inside Ruby Array

Interview Question on Ruby on Rails