检查给定字符串中是否存在数组元素

时间:2011-03-30 06:47:00

标签: ruby arrays

我有一行文字

this is the line

如果该数组中有一个元素,我想返回true

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

是上面给出的字符串的一部分。

因此对于上面的行,它应该返回true

对于这一行hello my name is martin,它不应该。

我知道include?但如果它有帮助我不知道如何使用它。

4 个答案:

答案 0 :(得分:24)

>> 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

答案 1 :(得分:15)

我知道测试将一个字符串包含在另一个字符串中的最简单方法是:

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

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

不需要正则表达式,或任何复杂的东西。

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)

答案 2 :(得分:6)

您可以将strling分割成一个数组,并检查数组与新拆分数组之间的交集,如下所示。

这很方便,因为它会给你不仅仅是一个真假,它会给你匹配的字符串。

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

如果你需要一个真/假,你可以很容易地做到:

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

答案 3 :(得分:1)

> 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