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#integer_at

integer_at(specifier, *to_i_args)

Returns the captured substring at the given specifier as an Integer, following the behavior of String#to_i(base).

specifier can be an Integer (positive, negative, or zero), a Symbol, or a String for named capture groups.

Returns nil if: - No match has been performed or the last match failed - The specifier is an Integer and is out of range - The group at specifier did not participate in the match

Raises IndexError if specifier is a Symbol or String that does not correspond to a named capture group, consistent with StringScanner#[].

This is semantically equivalent to self[specifier]&.to_i(base) but avoids the allocation of a temporary String when possible.

Example
scanner = StringScanner.new("2024-06-15")
scanner.scan(/(\d{4})-(\d{2})-(\d{2})/)
scanner.integer_at(1)       # => 2024
scanner.integer_at(1, 16)   # => 8228