Radek
Radek

Reputation: 11121

reverse include for array?

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

Upvotes: 0

Views: 669

Answers (3)

mu is too short
mu is too short

Reputation: 434865

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?

Upvotes: 3

ctide
ctide

Reputation: 5257

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.

Upvotes: 1

seph
seph

Reputation: 6076

try this:

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

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

Upvotes: 2

Related Questions