繁体   English   中英

如何在ruby中检查字符串是否包含字符串数组中的任何一个

[英]How to check in ruby if an string contains any of an array of strings

我有一个字符串数组a ,我想检查另一个长字符串b包含该数组中的任何字符串

a = ['key','words','to', 'check']
b = "this is a long string"

我必须有哪些不同的选择来完成此任务?

例如,这似乎有效

not a.select { |x| b.include? x }.empty?

但是它返回了否定的答案,那就是为什么我not其他任何想法或不同的方式?

您可以使用#any吗?

a = ['key','words','to', 'check']
b = "this is a long string"
a.any? { |s| b.include? s }

或类似使用::union东西。 但是根据需要,您可能需要更改正则表达式,在某种程度上可以做到。 如果没有,那么我将继续以上。

a = ['key','words','to', 'check'] 
Regexp.union a
# => /key|words|to|check/ 
b = "this is a long string"
Regexp.union(a) === b # => false 

您还可以使用数组交集( #& )方法:

a = ['key','words','to', 'check']
b = "this is a long string"
shared = a & b.gsub(/[.!?,'"]/, "").split(/\s/)

这将返回包含所有共享字符的数组。

扫描并展平

有多种方法可以执行您想要的操作,但是即使目的更加冗长,我还是喜欢为清晰起见而编写程序。 对我来说最好的方法是扫描数组中每个成员的字符串,然后查看展平结果是否包含任何成员。 例如:

a = ['key','words','to', 'check']
b = "this is a long string"
a.map { |word| b.scan /#{word}/ }.flatten.any?
# => false

a << 'string'
a.map { |word| b.scan /#{word}/ }.flatten.any?
# => true

起作用的原因是扫描返回了一个匹配数组,例如:

=> [[], [], [], [], ["string"]]

Array#flatten确保删除空的嵌套数组,以便Enumerable#any? 表现出您所期望的方式。 要了解为什么需要#flatten,请考虑以下因素:

[[], [], [], []].any?
# => true
[[], [], [], []].flatten.any?
# => false

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM