Подтвердить что ты не робот

Проверьте, существует ли элемент массива частично в заданной строке

У меня есть строка текста

this is the line

и я хочу вернуть true, если один из элементов в этом массиве:

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

является частью строки, указанной выше.

Итак, для строки выше он должен возвращать true.

Для этой строки hello my name is martin это не должно быть.

Я знаю include?, но я не знаю, как использовать его здесь, если он вообще помогает.

4b9b3361

Ответ 1

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

Ответ 2

Самый простой способ, который я знаю, чтобы проверить включение одной строки внутри другой:

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)

Ответ 3

Вы можете разбить строку на массив и проверить пересечение между вашим массивом и новым разделенным массивом, например.

Это удобно, потому что это даст вам больше, чем истинное значение false, оно даст вам соответствие строк.

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

Если вам нужен true/false, вы можете легко сделать:

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

Ответ 4

> 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