I am using Ruby 1.9.3. I was playing with some patterns and found something interesting:
Example 1:
irb(main):001:0> /hay/ =~ 'haystack'
=> 0
irb(main):003:0> /st/ =~ 'haystack'
=> 3
Example 2:
irb(main):002:0> /hay/.match('haystack')
=> #<MatchData "hay">
irb(main):004:0> /st/.match('haystack')
=> #<MatchData "st">
=~ returns the first location of its first match, whereas match returns the pattern. Other than that, is there any difference between =~ and match()?
Execution time difference (As per @Casper)
irb(main):005:0> quickbm(10000000) { "foobar" =~ /foo/ }
Rehearsal ------------------------------------
8.530000 0.000000 8.530000 ( 8.528367)
--------------------------- total: 8.530000sec
user system total real
8.450000 0.000000 8.450000 ( 8.451939)
=> nil
irb(main):006:0> quickbm(10000000) { "foobar".match(/foo/) }
Rehearsal ------------------------------------
15.360000 0.000000 15.360000 ( 15.363360)
-------------------------- total: 15.360000sec
user system total real
15.240000 0.010000 15.250000 ( 15.250471)
=> nil
First make sure you’re using the correct operator:
=~is correct,~=is not.The operator
=~returns the index of the first match (nilif no match) and stores theMatchDatain the global variable$~. Named capture groups are assigned to a hash on$~, and, when theRegExpis a literal on the left side of the operator, are also assigned to local variables with those names.The method
matchreturns theMatchDataitself (again,nilif no match). Named capture groups in this case, on either side of the method call, are assigned to a hash on the returnedMatchData.See http://www.ruby-doc.org/core-1.9.3/Regexp.html (as well as the sections on
MatchDataandString) for more details.