簡體   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