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

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.

Tags:

Ruby