Bug #1749

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

Added by runpaint (Run Paint Run Run) almost 3 years ago. Updated about 1 year ago.

[ruby-core:24223]
Status:Closed Start date:07/09/2009
Priority:Normal Due date:
Assignee:- % Done:

0%

Category:core
Target version:1.9.2
ruby -v:ruby 1.9.2dev (2009-07-08 trunk 23995) [i686-linux]

Description

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? :-)

History

Updated by yugui (Yuki Sonoda) almost 3 years ago

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

Updated by akr (Akira Tanaka) almost 3 years ago

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.

Updated by akr (Akira Tanaka) almost 3 years ago

  • Assignee deleted (akr (Akira Tanaka))

Updated by runpaint (Run Paint Run Run) almost 3 years ago

> 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.

Updated by naruse (Yui NARUSE) almost 3 years ago

  • Status changed from Open to Closed

Also available in: Atom PDF