给定这个数组:
["/Item A/", "/Item B/"]
还有一行:
Here's a line of text that includes /Item B/
什么是一种好的、惯用的 Ruby 方法来检查该行是否至少包含数组中的一个短语?
最佳答案
几种方式。速度可能取决于阵列和线的大小。可能需要运行一些基准测试来查看:
> a = ["/Item A/", "/Item B/"]
> l = "Here's a line of text that includes /Item B/"
然后使用 any?
:
> a.any?{|e| l.index(e)}
=> true
或者使用正则表达式:
> l =~ Regexp.union(a)
=> 36
关于Ruby - 数组中至少有一项也符合要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30851721/