开发者

Determining if an array of strings contains a certain substring in ruby

开发者 https://www.devze.com 2023-01-16 04:27 出处:网络
I have a simple ruby question.I have an array of strings.I\'d like to determine if that array contains a substring of any of the strings. As an example

I have a simple ruby question. I have an array of strings. I'd like to determine if that array contains a substring of any of the strings. As an example

a = ['cat','dog','elephant']
a.to_s.开发者_如何学JAVAinclude?('ele')

Is this the best way to do it?

Thanks.


a.any? should do the job.

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


Here is one more way: if you want to get that affected string element.

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

if you just want Boolean value only.

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

Hope this is helpful.

0

精彩评论

暂无评论...
验证码 换一张
取 消