Home > Net >  Check if strings in array includes a substring in another array
Check if strings in array includes a substring in another array

Time:11-22

I have a string in an array:

string_array = ["[email protected]", "[email protected]"]
domains = ["@domain.com.au", "firstname"]

and I need to remove any matches where the strings in the above array contains a substring from another array.

I've tried the below:

test = string_array.reject { |item| domains.include?(item) }
#=> ["[email protected]", "[email protected]"]

It should be the other way around, right? something like

test = string_array.reject { |item| item.include?(domains) }

But that raises TypeError: no implicit conversion of Array into String

CodePudding user response:

I would do this:

string_array = ["[email protected]", "[email protected]"]
domains = ["@domain.com.au", "firstname"]

string_array.reject { |email| domains.any? { |domain| email.include?(domain) } }
#=> ["[email protected]"]

The reason your version doesn't work, is because you compared a string with an array of strings. And because the exact substring is not included in the array, there is no match. Instead, you have to compare each string with it is a substring of any other string.

CodePudding user response:

You can build a regular expression matching all of your substrings via Regexp.union and then filter out anything that doesn't match via grep_v:

string_array = ["[email protected]", "[email protected]"]
domains = ["@domain.com.au", "firstname"]

string_array.grep_v(Regexp.union(domains))
#=> ["[email protected]"]

Note that instead of substrings you can also use other regular expressions with Regexp.union, e.g. /@domain\.com\.au\z/ to make the domain only match at the end of a string (\z is Ruby's end-of-string anchor)

  • Related