String#match shim for Ruby 1.6

How do I shim 1.6 for String.match?

I've tried,

unless String::respond_to?(:match)
  class String
   def match(regex)
    regex.match(self)
   end
end

but it doesn't set the group match variables, e.g.,
$1, $2, and so forth.

(Note: the above doesn't even attempt to deal with
converting a string to a regexp as 1.8's String.match
does.)

Thanks,

···

--
Bil
http://fun3d.larc.nasa.gov

Hi --

How do I shim 1.6 for String.match?

I assume there are answers to the obvious questions (Why not
Regexp#match? Why not 1.8.x?) so I won't ask them :slight_smile:

I've tried,

unless String::respond_to?(:match)

(Is the :: thing only used by gov't employees? :slight_smile:

I think you'd want:

   unless String.instance_methods.include?("match")

class String
  def match(regex)
   regex.match(self)
  end
end

but it doesn't set the group match variables, e.g.,
$1, $2, and so forth.

They'll get set inside the method, but not beyond. I think the
rationale for this is that otherwise you'd have no sane way of knowing
whether and when they were getting set:

   re = /(blah)/
   re.match(string)
   some_method(whatever)

   # did some_method do a match operation? did it reset the
   # capture variables?

David

···

On Wed, 9 Nov 2005, Bil.Kleb@gmail.com wrote:

--
David A. Black
dblack@wobblini.net

I got the '::' from the IO.read that ts gave me.

So, then my question becomes, can I create
a shim for 1.8's String#match with pure Ruby?

Thanks,

···

--
Bil
http://fun3d.larc.nasa.gov

I fear the closest you can get would be

    class String
      def match(re,&b)
  r = re.match(self)
  eval("lambda{|m| $~ = m}", b).call($~)
  r
      end
    end

    "foo".match(/foo/) # => #<MatchData:0xb7d1f220>
    $& # => nil
    RUBY_VERSION # => "1.6.8"

Of course, you can also use Florian's Binding.of_caller to get the environment
of the caller and substitute it in the eval, but callcc is expensive [even my
my variant, which doesn't use it, is quite expensive and you can only have a
trace_func at a time...].

···

On Wed, Nov 09, 2005 at 04:02:12AM +0900, Bil.Kleb@gmail.com wrote:

I got the '::' from the IO.read that ts gave me.

So, then my question becomes, can I create
a shim for 1.8's String#match with pure Ruby?

--
Mauricio Fernandez

sorry, I meant

     "foo".match(/foo/){} # => #<MatchData:0xb7cc21e4>
      $& # => "foo"
      RUBY_VERSION # => "1.6.8"

···

On Wed, Nov 09, 2005 at 07:00:00AM +0900, Mauricio Fernández wrote:

    "foo".match(/foo/) # => #<MatchData:0xb7d1f220>
    $& # => nil
    RUBY_VERSION # => "1.6.8"

--
Mauricio Fernandez