From: 7stud -- Date: 2009-04-29T23:57:17+09:00 Subject: Re: Issue with regexp pattern matcher withing String#gsub Craig Jolicoeur wrote: > 7stud -- wrote: >> ...and that means the error message you posted can't occur. When I run >> the code: >> >> str = %q{src="/foo/bar.png"} >> >> str.gsub!( /src=(["'])\S+\?\d*\1/ ) { |s| s.split('?').first + $1 } >> >> there are no errors and no output. So you must have done something >> differently in your code. > > you don't get an error because your initial quote doesnt make the match. > I used the string you provided. Generally, if you want relevant help, you should post relevant data. >> The side effect of String#split is changing the value of $1. > > It doesn't in ruby 1.8.6: > /(.)/ =~ "abc" puts $1 "acb".split(" ") puts $1 --output:-- a a > It will if the split is done on a Regexp (but the OP wasn't doing that) > > irb(main):008:0> /(.)/ =~ "abc"; puts $1; "a b".split(/ /); puts $1 > a > nil My tests show that every string but " " causes split() to change the value of $1. The docs say that if the pattern given to split() is a single space, the string will be split on whitespace with runs of whitespace ignored, for example: result = "a b".split(" ") p result --output:-- ["a", "b"] So a string containing a single space is treated differently than other strings by split(). Why that would cause a different result for the value of $1, I have no idea. > ahh, interesting. thanks so much. I didn't realize that #split would > overwrite those [global variables]. > > What exactly does the split function set them to? "abcd" =~ /a(b)(c)d/ puts $~, $1, $2 --output:-- abcd b c #same program: "AAAxyzBBB".split(/x(y)z/) puts $~, $1, $2 --output:-- nil nil nil $1 is supposed to be the string that matches the first grouping of a successful match -- Posted via http://www.ruby-forum.com/.