From: Josh Cheek Date: 2011-08-29T10:43:07+09:00 Subject: Re: String#split resets regex captures variables (Ruby 1.8.7) --f46d042fd8f0321cab04ab9b0445 Content-Type: text/plain; charset=ISO-8859-1 On Sun, Aug 28, 2011 at 7:54 PM, Olivier Lance wrote: > Hi, > > I've just spent some time on this problem until I found the solution, > and I wanted to share it/ask for opinions on this: > > I've got a string on which I try to match a regexp. If it matches, I > split the string with one of the captured groups, zip the resulting > array with an array of symbols and merge with a last symbol/string array > pair representing the captured separator. > > Here's some code to give you an idea: > > n = "a:c" > if n =~ /([a-z])([.:])([a-z])/ > p [:first, :second].zip(n.split($2)) | [[:separator, $2]] > end > > (see pastie here: http://pastie.org/2445983) > > > The problem is, the resulting array will contain "nil" for :separator. > Apparently, String#split will reset all regexp-related variables... I > guess it uses regexp internally, but I haven't seen anything documenting > this behavior, and I honestly believed this code would work... > > So what's your take on this? Does it feel natural/logical to you? > Should I file a bug to enhance Ruby's documentation? > > -- > Posted via http://www.ruby-forum.com/. > > It worked for me, you probably are using an old version of Ruby. RUBY_VERSION # => "1.9.2" n = "a:c" if n =~ /([a-z])([.:])([a-z])/ p [:first, :second].zip(n.split($2)) | [[:separator, $2]] end # >> [[:first, "a"], [:second, "c"], [:separator, ":"]] Anyway, why not just do [[:first, $1], [:second, $3], [:separator, $2]] --f46d042fd8f0321cab04ab9b0445--