我有一个字符串数组a
,我想检查另一个长字符串b
是否包含数组中的任何字符串。
a = ['key','words','to', 'check']
b = "this is a long string"
我有哪些不同的选项可以完成这个任务?
例如,以下方法似乎有效:
not a.select { |x| b.include? x }.empty?
但它返回了一个负面的响应,这就是为什么我使用了
not
,还有其他想法或不同的方法吗?include?
慢得多... - Uri Agassi有许多方法可以实现您想要的功能,但即使在代码变得更冗长时,我仍喜欢为清晰的目的编程。对我来说最好理解的方式是扫描字符串中的每个数组成员,然后查看展平的结果是否有任何成员。例如:
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
你也可以使用数组交集 (#&) 方法:
a = ['key','words','to', 'check']
b = "this is a long string"
shared = a & b.gsub(/[.!?,'"]/, "").split(/\s/)
这将返回一个包含所有共享字符的数组。
and
,or
和not
运算符时要小心,因为它们的优先级比赋值运算符低,应该使用&&
,||
和!
。 - Brandon Buck