0

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.

2
  • 1
    When I tried your code, the order was right. check out and run: repl.it/EA98/0 Commented Oct 19, 2016 at 14:48
  • Indeed, but I was missing the sort method at the end, that is why it did not return the array in the proper order. Commented Oct 19, 2016 at 17:28

1 Answer 1

2

I'd do something like this

example1.select { |syllable| example2.any? { |word| word.include? syllable } }
Sign up to request clarification or add additional context in comments.

4 Comments

It's more a substring than a syllable.
Yeah, I didn't know how to name it.
It works. Thanks You. I forgot to mention that the function did not work because it needed to be returned in a lexicographic order, which is simply done by calling sort
My pleasure Sir ;)

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.