From: "saddestmartian (sad mart) via ruby-core" Date: 2026-12-04T05:54:04+00:00 Subject: [ruby-core:127851] [Ruby Bug#22721] String#slice!(regexp, capture) returns a string with a stale coderange when capture.to_int modifies the receiver Issue #22721 has been reported by saddestmartian (sad mart). ---------------------------------------- Bug #22721: String#slice!(regexp, capture) returns a string with a stale coderange when capture.to_int modifies the receiver https://bugs.ruby-lang.org/issues/22721 * Author: saddestmartian (sad mart) * Status: Open * ruby -v: ruby 4.1.0dev (2026-12-03T23:00:19Z master bcd243e8e8) +PRISM [x86_64-linux] * Backport: 3.3: UNKNOWN, 3.4: UNKNOWN, 4.0: UNKNOWN ---------------------------------------- ```ruby s = "a�b" obj = Object.new obj.define_singleton_method(:to_int) { s.replace("��"); 0 } r = s.slice!(/�/, obj) r #=> "\xA9\xC3" r.valid_encoding? #=> true (r.b.force_encoding("UTF-8").valid_encoding? #=> false) ``` `rb_str_slice_bang` converts the capture argument after the regexp search; the conversion can run Ruby code that modifies the receiver. The existing guard ("Converting the backref may have modified the string.") clamps the offsets to the new length, but the piece is then cut from the new contents at the old offsets and gets the new contents' coderange, so a piece that splits a character is cached as valid. Possible fixes: raise like other "string modified" checks, take the piece from the MatchData, or clear the piece's coderange in this branch. Since the existing test `test_slice_bang_string_modified` shows that clamping was chosen deliberately for this spot, I have not prepared a patch. Reproduces on master and 4.0.10. -- https://bugs.ruby-lang.org/ ______________________________________________ ruby-core mailing list -- ruby-core@ml.ruby-lang.org To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org ruby-core info -- https://ml.ruby-lang.org/mailman3/lists/ruby-core.ml.ruby-lang.org/