String#match shim for Ruby 1.6

B

Bil.Kleb

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,
 
D

David A. Black

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 :)
I've tried,

unless String::respond_to?:)match)

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

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
 
B

Bil.Kleb

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,
 
M

Mauricio Fernández

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?

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

Mauricio Fernández

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

sorry, I meant

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


--=20
Mauricio Fernandez
 
B

Bil Kleb

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

Just to close this out:

Managed to have 1.8.2 installed by the powers that be
on a lumbering, old SGI Origin that only still lives
to be a slave to Ruby, which re-writes our Fortran
95 to use complex variables.

Later,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,261
Messages
2,571,041
Members
48,769
Latest member
Clifft

Latest Threads

Top