Bug #1749
closedChange in How $~ is Restored After String#sub/String#gsub with a Block
Description
=begin
I wrote the following in [ruby-core:23699], but it seems to have been missed, so I'm filing it as a ticket. There are 3 RubySpec failures relating to this issue, so it would be great to determine what's what. :-)
There's been a change between 1.8 and 1.9 in how $~ is restored after String#sub with a block. Upon leaving the #sub block, 1.8 restores $~ to what #sub set it to; 1.9 retains the value of $~ that was set inside the#sub block. The following code illustrates the issue:
[/./, "l"].each do |pattern|
old_md = nil
"hello".sub(pattern) do
old_md = $~
"ok".match(/./)
"x"
end
puts "$~ == old_md? #{$~ == old_md}" # A
puts "$~.string == 'hello'? #{$~.string == 'hello'}" # B
end
On 1.9.2 trunk, all conditionals are false; on 1.8.7/1.8.6 they're all true.
If you replace #sub with #gsub in the above example, the conditionals are still all true on 1.8. On 1.9 the $~.string conditionals (A) are now true. The MatchData comparison (B) appears to succeed from the
#inspect output, but the objects have different #hash codes, so they don't compare for equality.
Is this change intentional, or evidence of a regression? :-)
=end
Updated by yugui (Yuki Sonoda) about 15 years ago
- Assignee set to akr (Akira Tanaka)
- Target version set to 1.9.2
=begin
=end
Updated by akr (Akira Tanaka) about 15 years ago
=begin
I think 1.9.2 behaviour is no problem.
String#sub matches a regexp just once.
There is no reason to set $~ at last.
String#gsub matches a regexp repeatedly until it doesn't match.
It set the last match after match failure for later use.
=end
Updated by runpaint (Run Paint Run Run) about 15 years ago
=begin
I think 1.9.2 behaviour is no problem.
String#sub matches a regexp just once.
There is no reason to set $~ at last.String#gsub matches a regexp repeatedly until it doesn't match.
It set the last match after match failure for later use.
I don't understand why the change was made, but if you're saying it's intentional then I suppose we can close this ticket. I'll update the specs to indicate that this is a version-specific difference.
=end