Skip to content

Instantly share code, notes, and snippets.

@alecguintu
Created April 29, 2014 03:33
Show Gist options
  • Save alecguintu/11390085 to your computer and use it in GitHub Desktop.
Save alecguintu/11390085 to your computer and use it in GitHub Desktop.
Check if string contains any substring in an array in Ruby
require 'benchmark'
iterations = 1_000_000
words = 'foo, bar, test, boo'.split(',').map(&:strip)
string = 'this is going foo be awesome~!'
Benchmark.bmbm do |bm|
bm.report do
iterations.times do
words.any? { |s| string.include?(s) }
end
end
bm.report do
iterations.times do
r = Regexp.union(*words)
r === string
end
end
end
# Rehearsal ------------------------------------
# 0.800000 0.000000 0.800000 ( 0.804023)
# 14.990000 0.020000 15.010000 ( 15.017372)
# -------------------------- total: 15.810000sec
# user system total real
# 0.820000 0.000000 0.820000 ( 0.815677)
# 15.020000 0.020000 15.040000 ( 15.039478)
Benchmark.bmbm do |bm|
bm.report do
iterations.times do
words = 'foo, bar, test, boo'.split(',').map(&:strip)
string = 'this is going foo be awesome~!'
words.any? { |s| string.include?(s) }
end
end
bm.report do
iterations.times do
words = 'foo, bar, test, boo'.split(',').map(&:strip)
string = 'this is going foo be awesome~!'
r = Regexp.union(*words)
r === string
end
end
end
# Rehearsal ------------------------------------
# 4.710000 0.010000 4.720000 ( 4.711062)
# 20.080000 0.000000 20.080000 ( 20.085188)
# -------------------------- total: 24.800000sec
# user system total real
# 4.760000 0.000000 4.760000 ( 4.765137)
# 20.130000 0.010000 20.140000 ( 20.142866)
@monfresh
Copy link

monfresh commented Jun 3, 2014

Instead of this:

words = 'foo, bar, test, boo'.split(',').map(&:strip)

You can just do this:

words = %w(foo bar test boo)

@thegreyfellow
Copy link

Thanks for the benchmark 🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment