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