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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With