Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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.

like image 794
Dave G Avatar asked Sep 10 '10 16:09

Dave G


People also ask

How do you check if an array contains a value Ruby?

To check if a value is in the array, you can use the built-in include? method. The include? method returns true if the specified value is in the array and false if not.

How do you find the part of a string in Ruby?

A substring is a smaller part of a string, it's useful if you only want that specific part, like the beginning, middle, or end. How do you get a substring in Ruby? One way is to use a starting index & a number of characters, inside square brackets, separated by commas.


2 Answers

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 
like image 156
Shadwell Avatar answered Oct 17 '22 07:10

Shadwell


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.

like image 35
Piyush Awasthi Avatar answered Oct 17 '22 07:10

Piyush Awasthi