0

I want to check whether any item from the array is part of a string. Something like .include?

I wrote a function for that but I am sure there would be a simpler way.

Could someone suggest how I use less code to achieve the same?

$goes_into_cron_comments=["Edumate_upgrade","login"].map!{|item| item.downcase} 
params={}
params['run']="login_ldap"

def contains(array,string)
        array.each{|item| 
            if string.include?(string)
                return true
            end
        }
        return false
end
#if ($goes_into_cron_comments.include?(params['run'].downcase)) #original condition
if (contains($goes_into_cron_comments,params['run'].downcase))
    puts "contains"
else 
    puts "doesn't contain"
end
1

3 Answers 3

3

There are things you can do that would be nicer. You could use Enumerable#any? rather than iterating by hand:

array.any? { |item| string.include?(item) }

Or you could use Regexp.union:

string =~ Regexp.union(array)
# or if you want a true boolean
!!(string =~ Regexp.union(array))
!(string =~ Regexp.union(array)).nil?
Sign up to request clarification or add additional context in comments.

3 Comments

+1 Came here for the more-efficient regex answer, leaving extra satisfied due to the usage of union.
Why regex that more-efficient?
@Radek: The regex engine can look at all the elements of array at once so it may be faster for larger arrays.
2

try this:

str = 'hey, this is a string'
arr = %w{one hey may}

arr.any? { |el| str.include? el }
=> true 

Comments

1

I would just do something like this:

def contains?(array,string)
    array.index{|item| string.include?(item)}
end

Index will return a truthy/falsy value, so this is probably the 'cleanest' way to do it. I would also include the ? at the end of your function definition just to make it clearer how it should be used and what result to expect.

2 Comments

I changed my code to if ($goes_into_cron_comments.index{|item| params['run'].downcase.include?(item)}) and I am always getting true regardless if the array contains the correct string. In your code should be ... .include?(item) ...
Yeah, sorry, I didn't change that bit from your example :)

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.