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

Mar*_*sch 19 ruby arrays

我有一行文字

this is the line
Run Code Online (Sandbox Code Playgroud)

我想返回true该数组中的一个元素:

['hey', 'format', 'qouting', 'this']
Run Code Online (Sandbox Code Playgroud)

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

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

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

我知道,include?但如果它有帮助,我不知道如何在这里使用它.

Mic*_*ohl 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
Run Code Online (Sandbox Code Playgroud)

  • 这是一个正则表达式匹配.由于Ruby中的正则表达式支持字符串插值,我使用它来创建数组中的一个字符串. (2认同)
  • 我应该补充说,如果一个单词是字符串中较长单词的一部分,这也会返回true,所以如果你不想这样,你必须匹配单词边界`/\b#[w}\b/`. (2认同)

the*_*Man 15

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

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

words.any? { |w| text[w] }  #=> true
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

  • `text.include?w`建议它返回一个布尔值,是否```包含在`text`中.`text [w]`乍一看可能被解释为在`text`中给出`w`的起始值. (4认同)

jar*_*ine 6

您可以将strling分割成一个数组,并检查数组和新拆分数组之间的交集,就像这样.

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

> "this is the line".split(' ') & ["hey", "format", "quoting", "this"]
=> ["this"] 
Run Code Online (Sandbox Code Playgroud)

如果您需要真/假,您可以轻松地做到:

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