确定一个字符串数组是否包含ruby中的某个子字符串

时间:2010-09-10 16:48:19

标签: ruby

我有一个简单的红宝石问题。我有一个字符串数组。我想确定该数组是否包含任何字符串的子字符串。作为一个例子

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

这是最好的方法吗?

感谢。

2 个答案:

答案 0 :(得分:57)

a.any?应该完成这项工作。

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

答案 1 :(得分:0)

这是另一种方式: 如果要获取受影响的字符串元素。

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

如果您只想要布尔值。

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

希望这会有所帮助。

相关问题