Project

General

Profile

Bug #1749

Change in How $~ is Restored After String#sub/String#gsub with a Block

Added by runpaint (Run Paint Run Run) over 11 years ago. Updated over 9 years ago.

Status:
Closed
Priority:
Normal
Assignee:
-
Target version:
ruby -v:
ruby 1.9.2dev (2009-07-08 trunk 23995) [i686-linux]
Backport:
[ruby-core:24223]

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

#1

Updated by yugui (Yuki Sonoda) over 11 years ago

  • Assignee set to akr (Akira Tanaka)
  • Target version set to 1.9.2

=begin

=end

#2

Updated by akr (Akira Tanaka) over 11 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

#3

Updated by akr (Akira Tanaka) over 11 years ago

  • Assignee deleted (akr (Akira Tanaka))

=begin

=end

#4

Updated by runpaint (Run Paint Run Run) about 11 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

#5

Updated by naruse (Yui NARUSE) about 11 years ago

  • Status changed from Open to Closed

=begin

=end

Also available in: Atom PDF