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
re.c
View on GitHub ↗
static VALUE
match_integer_at(int argc, VALUE *argv, VALUE match)
{
match_check(match);
int base = 10;
VALUE idx;
int nth;
argc = rb_check_arity(argc, 1, 2);
if (FIXNUM_P(idx = argv[0])) {
nth = NUM2INT(idx);
}
else if ((nth = namev_to_backref_number(match, idx)) < 0) {
name_to_backref_error(idx);
}
if (argc > 1 && (base = NUM2INT(argv[1])) < 0) {
rb_raise(rb_eArgError, "invalid radix %d", base);
}
if (nth >= RMATCH_NREGS(match)) return Qnil;
if (nth < 0 && (nth += RMATCH_NREGS(match)) <= 0) return Qnil;
rb_len_t start = RMATCH_BEG(match, nth), end = RMATCH_END(match, nth);
if (start < 0) return Qnil;
RUBY_ASSERT(start <= end, "%"PRIdLEN" > %"PRIdLEN, start, end);
VALUE str = RMATCH(match)->str;
RUBY_ASSERT(end <= RSTRING_LEN(str), "%"PRIdLEN" > %"PRIdLEN, end, RSTRING_LEN(str));
char *endp;
return rb_int_parse_cstr(RSTRING_PTR(str) + start, end - start, &endp, NULL,
base, RB_INT_PARSE_DEFAULT);
}
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
-
4.1
-
MatchData#integer_atis added. It converts the matched substring to integer and return the result. [Feature #21932]
-