Library contents

Ruby Kernel#Integer

Integer converts its argument using a specified base. With exception: false an unsuccessful conversion returns nil.

A simple example

Kernel#Integer

  1. Start with "12"
  2. Do this Read a base-ten integer
  3. Result 12
The characters 1 and 2 represent one ten and two ones. The resulting number can be used in arithmetic.

Syntax

Ruby 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.

First output line0
lesson.rb
['0', '08', '8kg'].each do |text|
  value = Integer(text, 10, exception: false)
  puts value.nil? ? 'invalid' : value
end
Output
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

Advertisements

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?

Given“18” + 2 on hand
Worked result20

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?

Given“0” + 2 on hand
Worked result2