Ruby Kernel#Integer
Integer converts its argument using a specified base. With exception: false an unsuccessful conversion returns nil.
A simple example
Kernel#Integer
- Start with "12"
- Do this Read a base-ten integer
- Result 12
Syntax
value = Integer(text, 10, exception: false)
Run this example in Ruby
Save the program as lesson.rb. Use Ruby 2.6 or later.
ruby lesson.rb
Read integer fields with a deliberate failure policy
A shipment or sensor form accepts a number as text. Check both the allowed range and how much input was consumed so a partial number, invalid field or overflowing value cannot pass as a normal reading.
['0', '08', '8kg'].each do |text|
value = Integer(text, 10, exception: false)
puts value.nil? ? 'invalid' : value
end
0 8 invalid
Fixing the base at ten keeps a leading zero from selecting another base. An explicit nil test preserves a successfully parsed numeric zero.
Ruby documentation for Kernel#Integer
Read the afternoon delivery
A store receives a quantity as text from a barcode reader. Read the whole decimal quantity and add it to the two units already at the desk. What total should the register show?
Read an empty delivery count
A class receives a stock record whose quantity field is the character zero. Read the whole decimal quantity and add it to the two units already at the desk. What total should the register show?