开发者

Check if an element of an array partly exists in a given string

I have a line of text

this is the line

and I want to return true if one of the element开发者_运维百科s in that array:

['hey', 'format', 'qouting', 'this']

is a part of the string given above.

So for the line above it should return true.

For this line hello my name is martin it should not.

I know include? but I don't know how to use it here if it helps at all.


>> s = "this is the line"
=> "this is the line"
>> ['hey', 'format', 'qouting', 'this'].any? { |w| s =~ /#{w}/ }
=> true
>> ['hey', 'format', 'qouting', 'that'].any? { |w| s =~ /#{w}/ }
=> false
>> s2 = 'hello my name is martin'
=> "hello my name is martin"
>> ['hey', 'format', 'qouting', 'this'].any? { |w| s2 =~ /#{w}/ }
=> false


The simplest way I know to test for inclusion of one string inside another is:

text = 'this is the line'
words = ['hey', 'format', 'qouting', 'this']

words.any? { |w| text[w] }  #=> true

No need for regex, or anything complicated.

require 'benchmark'

n = 200_000
Benchmark.bm(3) do |x|
  x.report("1:") { n.times { words.any? { |w| text =~ /#{w}/ } } }
  x.report("2:") { n.times { text.split(" ").find { |item| words.include? item } } }
  x.report("3:") { n.times { text.split(' ') & words } }
  x.report("4:") { n.times { words.any? { |w| text[w] } } }
  x.report("5:") { n.times { words.any? { |w| text.include?(w) } } }
end

>>          user     system      total        real
>> 1:   4.170000   0.160000   4.330000 (  4.495925)
>> 2:   0.500000   0.010000   0.510000 (  0.567667)
>> 3:   0.780000   0.030000   0.810000 (  0.869931)
>> 4:   0.480000   0.020000   0.500000 (  0.534697)
>> 5:   0.390000   0.010000   0.400000 (  0.476251)


You could split the strling into an array, and check for the intersection between your array and the newly split array, like so.

This is handy because it'll give you more than a true false, it will give you the matched strings.

> "this is the line".split(' ') & ["hey", "format", "quoting", "this"]
=> ["this"] 

If you needed a true / false you could easily do:

> s = "this is the line"
=> "this is the line" 
> intersection = s.split(' ') & ["hey", "format", "quoting", "this"]
=> ["this"] 
> intersection.empty?
=> false


> arr = ['hey', 'format', 'qouting', 'this']
=> ["hey", "format", "qouting", "this"]
> str = "this is the line"
=> "this is the line"
> str.split(" ").find {|item| arr.include? item }
=> "this"
> str.split(" ").any? {|item| arr.include? item }
=> true
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜