Leo
Leo

Reputation: 129

Verify if substring included in string when comparing away elements

I have two data sets

example1 = ["og", "phan"]
example2 = ["dog", "cat", "elephant", "chicken", "snake"]

What I need to be returned, exactly, is a new array containing elements from example1 only if they are substring of any of the elements of example2 and they should also be included in the same order as they were presented.

I managed to get the following code working, but the new array returns the elements in a different order (e.g. ["phan", "og"] instead of ["og", "phan"].

r = []
array1.map { |x| r.push(x) if array2.join(" ").include?(x) }
r.flatten

Extra: I found out that include? does not work if you use it when comparing array against array, in other words, it does not find substring within string in a single array element unless it is exactly the same.

Upvotes: 0

Views: 38

Answers (1)

Ursus
Ursus

Reputation: 30056

I'd do something like this

example1.select { |syllable| example2.any? { |word| word.include? syllable } }

Upvotes: 2

Related Questions