我有一行文字
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)
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)
您可以将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)
| 归档时间: |
|
| 查看次数: |
11553 次 |
| 最近记录: |