鉴于此数组:
["/Item A/", "/Item B/"]
和一行:
Here's a line of text that includes /Item B/
检查该行是否至少包含一个来自数组的短语,这是一种好的,惯用的Ruby方法吗?
答案 0 :(得分:4)
几种方式。速度可能取决于阵列和线的大小。可能想要运行一些基准来看:
> a = ["/Item A/", "/Item B/"]
> l = "Here's a line of text that includes /Item B/"
然后使用any?
:
> a.any?{|e| l.index(e)}
=> true
或使用Regexp:
> l =~ Regexp.union(a)
=> 36
答案 1 :(得分:2)
以上回答非常好,您还可以使用any?
和include?
a = ["/Item A/", "/Item B/"]
l = "Here's a line of text that includes /Item B/"
a.any? { |e| l.include?(e) }
=> true
答案 2 :(得分:0)
如果数组的元素遵循模式,如您的示例所示,您可能希望使用正则表达式来提高效率。例如:
a = ("A".."X").map { |c| "/Item #{c}/" }
#=> ["/Item A/", "/Item B/", "/Item C/",..., "/Item X/"]
"I considered /Item Y/ and /Item R/. I want the R!" =~ /\/Item [A-X]\// #=> 26
"I considered /Item Y/ and /Item Z/. I want the Z!" =~ /\/Item [A-X]\// #=> nil