regex =~ string or string =~ regex?

R

Ruby Newbee

Sometime I saw you wrote regex =~ string, while sometime you wrote
string =~ regex.
What's their difference and what's the recommended way? Thanks.

Jenn.
 
R

Robert Klemme

Sometime I saw you wrote regex =~ string, while sometime you wrote
string =~ regex.
What's their difference and what's the recommended way? Thanks.

The first version invokes method Regexp#=~ and the second version
invokes String#=~ - which happen to do roughly the same although I
believe the second one to be a tad slower. I personally prefer the
first form because of the speed difference and regular expression
matching is rather an operation of Regexp than of String.

Kind regards

robert
 
M

Marnen Laibow-Koser

Robert said:
The first version invokes method Regexp#=~ and the second version
invokes String#=~ - which happen to do roughly the same although I
believe the second one to be a tad slower. I personally prefer the
first form because of the speed difference and regular expression
matching is rather an operation of Regexp than of String.

Interesting. Whereas I prefer the second because I think
mystring =~ /foo/
is syntactically analogous to
mystring == 'foo'
Kind regards

robert

Best,
-- 
Marnen Laibow-Koser
http://www.marnen.org
(e-mail address removed)
 
K

Kirk Haines

The first version invokes method Regexp#=3D~ and the second version invok= es
String#=3D~ - which happen to do roughly the same although I believe the
second one to be a tad slower. =A0I personally prefer the first form beca= use
of the speed difference and regular expression matching is rather an
operation of Regexp than of String.

Very technically speaking, calling the Regexp#=3D~ will be
microscopically faster because it avoids a tiny bit of C code that
gets executed when calling the String#=3D~ version. In practice though,
the difference is so small as to be invisible against the noise of the
rest of the system.

String#=3D~ just has a little sugar built in.

If it's passed a Regexp, then it just calls the C function underlying Regex=
p#=3D~.
If it is passed a String, it complains.
If it is passed anything else, it tries to call #=3D~ on what it was
passed, passing itself as the argument. This lets one build custom
matching classes that Strings can use with the =3D~ syntax.


Kirk Haines
 

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

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top