在 Ruby 中确定字符串数组是否包含特定子串

47

我有一个简单的 Ruby 问题。我有一个字符串数组,我想确定该数组是否包含任何一个字符串的子字符串。例如:

a = ['cat','dog','elephant']
a.to_s.include?('ele')

这是最好的做法吗?

谢谢。


1
你想要得到 ['cat','dog','elephant']'gel'truefalse 吗? - sepp2k
有什么办法可以获取包含子字符串的元素数组? - Surya
2个回答

88

a.any?应该可以完成任务。

> a = ['cat','dog','elephant']
=> ["cat", "dog", "elephant"]
> a.any? { |s| s.include?('ele') }
=> true
> a.any? { |s| s.include?('nope') }
=> false

有没有一种方法可以检查多个值? - Shiko
你需要进行嵌套的 any? 检查,可能需要不同的问题,虽然简短的答案可能是:a.any? { |s| ['aba', 'ele'].any? { |t| s.include?(t) } } - Shadwell
2
我最终的代码是:haystack.select { |str| str.include?('wat') || str.include?('pre') } - Shiko
谢谢您的评论。 - Shiko

14

这里还有另一种方法:如果你想获得那个受影响的字符串元素。

>  a = ['cat','dog','elephant']
=> ["cat", "dog", "elephant"]
> a.grep(/ele/)
=> ["elephant"]

如果你只想要布尔值。

> a.grep(/ele/).empty?
=> false # it return false due to value is present

希望这对你有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接