Project

General

Profile

Actions

Bug #16448

closed

regex global variables are working differently depending on scope

Added by tdrive (Stanislav Boldaev) almost 5 years ago. Updated over 3 years ago.

Status:
Closed
Assignee:
-
Target version:
-
ruby -v:
ruby 2.6.5p114 (2019-10-01 revision 67812) [x86_64-darwin18]
[ruby-core:96429]
Tags:

Description

Hi, everyone.

I am trying to write a code similar to this

#!/usr/bin/env ruby

def check(f1)
  f2 = ->(match) { p match; p $~ }
  
  data = "hello test test test"
  
  data.gsub(/test/, &f1)
  data.gsub(/test/, &f2)
end

check(->(match) { p match; p $~ })

output:

"test"
nil
"test"
nil
"test"
nil
"test"
#<MatchData "test">
"test"
#<MatchData "test">
"test"
#<MatchData "test">

ruby versions:
ruby 2.6.5p114 (2019-10-01 revision 67812) [x86_64-darwin18]
ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-darwin18]

Why does the global variable ($~) in f1 and f2 work differently? It's a bug or my mistake?


Related issues 1 (1 open0 closed)

Related to Ruby master - Bug #8444: Regexp vars $~ and friends are not thread localAssignedko1 (Koichi Sasada)Actions

Updated by mame (Yusuke Endoh) almost 5 years ago

$~ is not a global variable, but a kind of local variable. String#gsub assigns the match data to $~ of its caller. data.gsub(/test/, &f1) assigns $~ of the scope of check. The lambda f1 reads $~ of the toplevel scope, which is not set.

You can see the behavior by the following code:

def check(f1)
  data = "foobar"

  data.gsub(/foo/, &f1) #=> #<MatchData "DUMMY">
  p $~                  #=> #<MatchData "foo">

  f2 = ->(match) { p $~ }

  data.gsub(/bar/, &f2) #=> #<MatchData "bar">
  p $~                  #=> #<MatchData "bar">
end

"DUMMY" =~ /DUMMY/
check(->(match) { p $~ })

Updated by tdrive (Stanislav Boldaev) almost 5 years ago

It is very unexpected.(
Thank you.

Actions #3

Updated by sawa (Tsuyoshi Sawada) almost 5 years ago

  • Subject changed from regex global variables are working differently depend on scope to regex global variables are working differently depending on scope
  • Description updated (diff)
Actions #4

Updated by jeremyevans0 (Jeremy Evans) almost 5 years ago

  • Related to Bug #8444: Regexp vars $~ and friends are not thread local added
Actions #5

Updated by jeremyevans0 (Jeremy Evans) over 3 years ago

  • Status changed from Open to Closed
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0