Skip to content

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

instance method · added in Ruby 4.1

MatchData#integer_at

integer_at(index, base = 10) → integer or nil
integer_at(name, base = 10) → integer or nil

Converts the matched substring to integer and return the result. +$~.integer_at(N)+ is equivalent to +$N&.to_i+.

Example
m = /(\d+{4})(\d+{2})(\d+{2})/.match("20260308")
# => #<MatchData "20260308" 1:"2026" 2:"03" 3:"08">
m.integer_at(0)     # => 20260308
m.integer_at(1)     # => 2026
m.integer_at(2)     # => 3
m.integer_at(3)     # => 8

m = /(?<y>\d+{4})(?<m>\d+{2})(?<d>\d+{2})/.match("20260308")
m.integer_at("y")   # => 2026
m.integer_at("m")   # => 3
m.integer_at("d")   # => 8

If the substring does not match, returns nil.

Example
re = /(\d+)?/
re.match("123").integer_at(1) #=> 123
re.match("abc").integer_at(1) #=> nil

The string is converted in decimal by default.

Example
/\d+/.match("011").integer_at(0)     #=> 10
/\d+/.match("011").integer_at(0, 12) #=> 13
/\d+/.match("011").integer_at(0, 0)  #=> 9

See also MatchData#[], String#to_i.

Ruby version changes

  1. 4.1