Which one is better? It is not easy to answer the question, because they do not all do the same thing.
x == 'abc' || x == 'def' || x == 'ghi' %w(abc def ghi).include? x
compare x with fixed rows for equality. x must be one of these values. Between the two, I tend to go with the second, because it is easier to maintain. Imagine what it would look like if you had to compare against twenty, fifty or hundreds of lines.
Third test:
x ~= /abc|def|ghi/
matches substrings:
x = 'xyzghi' (x =~ /abc|def|ghi/)
so this is not the same as the first two.
EDIT: In the tests we did, there are some things that I would do differently. Using Ruby 1.9.2-p180 on a MacBook Pro, it checks 1,000,000 loops and compares the results of regular expression bindings using grouping, and also without breaking the %w() array every time through the loop:
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
the tin man
source share