48

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.

2
  • 1
    Would you want to get true or false for ['cat','dog','elephant'] and 'gel'? Commented Sep 10, 2010 at 16:54
  • any idea on how to get array of elements that has the substring? Commented Aug 29, 2018 at 12:38

2 Answers 2

89

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
Sign up to request clarification or add additional context in comments.

3 Comments

Is there a way to check multiple values ?
You'd need to do a nested any? check and probably a different question although a short answer might be: a.any? { |s| ['aba', 'ele'].any? { |t| s.include?(t) } }
I ended with this haystack.select { |str| str.include?('wat') || str.include?('pre') }
14

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.