Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

StringScanner#scan_integer

scan_integer(base: 10) → integer or nil

Returns an integer scanned from self, beginning at the current position; returns nil if no such integer was available.

When base is 10 (the default), equivalent to calling scan with argument pattern as '[+-]?\d+':

Example
scanner = StringScanner.new('Form 27B/6')
scanner.scan_integer # => nil # No integer at position 0.
scanner.pos = 5
scanner.scan_integer # => 27
scanner.matched      # => "27"
scanner.pos          # => 7

When base is 16 (the only other value allowed), equivalent to calling scan with argument pattern as '[+-]?(0x)?[0-9a-fA-F]+':

Example
scanner.pos = 5
scanner.scan_integer(base: 16) # => 635
scanner.matched                # => "27B"
scanner.pos                    # => 8

Raises Encoding::CompatibilityError if self does not have an ASCII compatible encoding.

See also #scan_byte #scan_until #scan #size also in 4.0