You'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]
(written 2010-02-01 22:28:56)
Associated topics are indexed under
R111 - Ruby - Exceptions. [2622] Handling unusual and error conditions - exceptions - (2010-02-03)
[2621] Ruby collections and strings - some new examples - (2010-02-03)
[2620] Direct access to object variable (attributes) in Ruby - (2010-02-02)
[1875] What are exceptions - Python based answer - (2008-11-08)
Some other Articles
Passing code to procedures and yield in RubyWhat are Ruby Symbols?Comparing floating point numbers - a word of caution and a solutionDefining a static method - Java, Python and RubyString to number conversion with error trapping in RubyNeatly formatting results into a tableConstants in RubyThe Model, View, Controller architecture (MVC) - what, why and how.Sunday Evening, City of LondonCheat Sheet - what do you need for Ruby on Rails?