检查字符串变量是否在一组字符串中

Vin*_*ent 6 ruby

哪一个更好:

x == 'abc' || x == 'def' || x == 'ghi'
%w(abc def ghi).include? x
x =~ /abc|def|ghi/
Run Code Online (Sandbox Code Playgroud)

the*_*Man 7

哪一个更好?这个问题不容易回答,因为他们并非都做同样的事情.

x == 'abc' || x == 'def' || x == 'ghi'
%w(abc def ghi).include? x
Run Code Online (Sandbox Code Playgroud)

比较x固定字符串的相等性.x必须是这些价值观之一.在这两者之间,我倾向于选择第二种,因为它更容易维护.想象一下,如果必须与二十,五十或一百个字符串进行比较,它会是什么样子.

第三次测试:

x ~= /abc|def|ghi/
Run Code Online (Sandbox Code Playgroud)

匹配子串:

x = 'xyzghi'
(x =~ /abc|def|ghi/) # => 3
Run Code Online (Sandbox Code Playgroud)

所以它与前两个不一样.

编辑:纳什完成的基准测试中有一些事情我会采用不同的方式.在MacBook Pro上使用Ruby 1.9.2-p180,这将测试1,000,000个循环,并使用分组比较锚定正则表达式的结果,以及%w()每次循环时不拆分数组:

require 'benchmark'
str = "test"

n = 1_000_000
Benchmark.bm do |x|
  x.report { n.times { str == 'abc' || str == 'def' || str == 'ghi' } }
  x.report { n.times { %w(abc def ghi).include? str } }
  x.report { ary = %w(abc def ghi); n.times { ary.include? str } }
  x.report { n.times { str =~ /abc|def|ghi/ } }
  x.report { n.times { str =~ /^abc|def|ghi$/ } }
  x.report { n.times { str =~ /^(abc|def|ghi)$/ } }
  x.report { n.times { str =~ /^(?:abc|def|ghi)$/ } }
  x.report { n.times { str =~ /\b(?:abc|def|ghi)\b/ } }
end
# >>       user     system      total        real
# >>   1.160000   0.000000   1.160000 (  1.165331)
# >>   1.920000   0.000000   1.920000 (  1.920120)
# >>   0.990000   0.000000   0.990000 (  0.983921)
# >>   1.070000   0.000000   1.070000 (  1.068140)
# >>   1.050000   0.010000   1.060000 (  1.054852)
# >>   1.060000   0.000000   1.060000 (  1.063909)
# >>   1.060000   0.000000   1.060000 (  1.050813)
# >>   1.050000   0.000000   1.050000 (  1.056147)
Run Code Online (Sandbox Code Playgroud)