问题描述:

Two expressions:

puts "String has vowels" if "This is a test".match(/[aeiou]/)

and

puts "String has vowels" if "This is a test" =~ /[aeiou]/

seem identical. Are they not? I did some testing below:

"This is a test" =~ /[aeiou]/

# => 2

"This is a test".match(/[aeiou]/)

# => MatchData "i"

So it seems like =~ gives you the position of the first match and match method gives you the first character that matches. Is this correct? They both return true and so what's the difference here?

网友答案:

They just differ on what they return if there is a match. If there is no match, both return nil.

~= returns the numerical index of the character in the string where the match started
.match returns an instance of the class MatchData

网友答案:

You're correct.

Expanding on Nobita's answer, match is less efficient if you want to just check to see if a string matches a regexp (like in your case). In that case, you should use =~. See the answer to "Fastest way to check if a string matches or not a regexp in ruby?", which contains these benchmarks:

require 'benchmark'

"test123" =~ /1/
=> 4
Benchmark.measure{ 1000000.times { "test123" =~ /1/ } }
=>   0.610000   0.000000   0.610000 (  0.578133)

...

irb(main):019:0> "test123".match(/1/)
=> #<MatchData "1">
Benchmark.measure{ 1000000.times { "test123".match(/1/) } }
=>   1.703000   0.000000   1.703000 (  1.578146)

So, in this case, =~ is a little less than three times faster than match

相关阅读:
Top