Hacker621
Hacker621

Reputation: 55

Determining if a string contains any of the value that is present in an array in ruby

I have a simple ruby question. I have an array of strings. I'd like to determine if a variable contains any of the string present in that array.

As an example

Lets say

my_string = "testing.facebook.com"

array = ["google.com","facebook.com","github.com"]

Then I need to check whether my_string has any one of value that is present in the array.

For above scenario It will return true since "facebook.com" is present in my_string

I have tried below code

This below code will work but i don't think this is an optimized way

if my_string.include?("google.com") || my_string.include?("facebook.com") || my_string.include?("github.com")
// execute something
end

Please provide a optimized solution or a better way through which i can do this

Upvotes: 1

Views: 1155

Answers (2)

Richard-Degenne
Richard-Degenne

Reputation: 2949

Tom Lord's answer is perfectly correct, but here is an additional tool in Ruby's belt.

You can use Enumerable#detect to get the element that matched, if any.

def match(string)
  %w[google.com facebook.com github.com].detect { |item| string.include?(item) }
end

match('testing.facebook.com')
# => "facebook.com"

match('stackoverflow.com')
# => nil

Upvotes: 1

Tom Lord
Tom Lord

Reputation: 28285

Here's how I would write it:

my_string = "testing.facebook.com"
array = ["google.com","facebook.com","github.com"]

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

This uses Enumerable#any?.

Enumerable is a module which is included in the Array class, amongst others.

Upvotes: 5

Related Questions