What are the empty single quotes for after rescue?

123 Views Asked by At
 while t = Integer(gets.chomp) rescue ''
   if t.is_a? Integer
    break
   else
    print "Please enter a whole number "
   end
  end 

I'm just trying to figure out exactly why I need those empty single quotes after rescue for this loop to work.

2

There are 2 best solutions below

0
Alexey On

because Integer(gets.chomp) can raise an exception, which caught by rescue and assign to t value as empty string

0
Michael Kohl On

This is referred to as an inline rescue. If t = Integer(gets.chomp) raises any exception inheriting from StandardError it will be rescued and an empty string will be returned instead. You can think of it like this:

begin
  do_something
rescue
  ''
end

The problem with this approach is that you can't specify exception classes to rescue from, so you may accidentally mask errors that you didn't expect, like a NoMethodError raised when misspelling the chomp method:

Integer(gets.chmp) rescue ''
#=> ""