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.include?('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
any?
check and probably a different question although a short answer might be: a.any? { |s| ['aba', 'ele'].any? { |t| s.include?(t) } }
haystack.select { |str| str.include?('wat') || str.include?('pre') }
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.
true
orfalse
for['cat','dog','elephant']
and'gel'
?