Each iteration of String#scan should result in a unique MatchData returned by Regexp.last_match, with each MatchData object reflecting the results of its match. Thus if String#scan resulted in two matches, after the first match Regexp.last_match would have different values than Regexp.last_match would have after the second match.
However, in the current implementation each MatchData resulting from an invocation of String#scan has the values of the most recent match. For example, from the attached unit test:
although they are different objects (per the object_id assertions) firstmatch and secondmatch have the same results, so the assertion:
will fail, with firstmatch equaling "ting", the results for the second match. (Note that this test succeeds with Ruby 1.8 and 1.9.)
The reason for this behavior is that during String#scan, a MatchData is created for each match. The MatchData object has an attribute "regs" (org.joni.Region), which refers to where the pattern matched in the string.
The issue is that when String#scan creates MatchData objects for each pattern match, each of the MatchData objects refer to the same Region instance. Subsequent matches result in the Region object being updated, and each MatchData object sharing a reference to that Region will have the same value, as used in MatchData#to_s and MatchData#captures.
The solution is to clone the Region object for each newly-created MatchData, as in the attached patch.