String to number conversion with error trapping in Ruby
Archive - Originally posted on "The Horse's Mouth" - 2010-02-01 22:28:56 - Graham EllisYou've read in a string of text in Ruby - perhaps the user's input, or perhaps from a file. You know that string shoould contain a number - so you use the to_i method to do the conversion. But there's a problem - if the string doesn't start with a number, it won't convert correctly - it will just return a zero. And you'll probably want to know there's a problem so that you can deal with it.
The solution is to use the built in Integer function and pass it the string - i.e. replace:
value = stuff.to_i
by
value = Integer(stuff)
When you run that code on a string that does correctly contain a string that converts to an integer, there's no difference to see in how you code works. But if there's an error, Integer throws an exception.
Include your Integer call within a begin and end block .. and within that block, also provide a rescue section. Ruby will start running the main part of the block when it arrives at that piece of the code, and if the main part of the block runs correctly it will skip the rescue section. But if something goes in the main section of the block, it will jump straight away to the rescue code.
Here's an example ... if there is a valid integer in the said string, it is added to total_so_far, and the goodvalues variable is incremented. But if there is not a number in said, then a controlled error message is generated:
begin
total_so_far += Integer(said)
goodvalues += 1
rescue
puts "Sorry - not accepted"
end
The complete example, with some sample results, is [here]