Created
April 29, 2014 03:33
-
-
Save alecguintu/11390085 to your computer and use it in GitHub Desktop.
Check if string contains any substring in an array in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Instead of this:
You can just do this: