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.
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.
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 ''
#=> ""
because Integer(gets.chomp) can raise an exception, which caught by rescue and assign to
tvalue as empty string