Carpela
Carpela

Reputation: 2195

Remove items (superstrings) from array where a substring exists as another item

I'm trying to filter an array where I want to exclude anything that has a 'substring' in the array. This is to create an array of search terms but limit the number of duplicate searches.

i.e.

[ "Rough Collie", "Alsatian", "Standard Poodle", "Poodle", "Collie", "Schnauser", "Border Collie", "Chihuahua" ]
=>
[ "Alsatian", "Poodle", "Collie", "Schnauser", "Chihuahua" ]

Where we've removed Standard Poodle, because Poodle is a match and Rough Collie and Border Collie because Collie is a match. i.e. if a word exists but also exists as a substring in another term, remove the longer term.

arr - arr.map { |a| arr.select { |s| s.include?(a) && s != a}}.flatten

this basically works but looks a bit ugly. Is there a more elegant way to do that?

Upvotes: 1

Views: 76

Answers (2)

Raman
Raman

Reputation: 1281

Another way can be as follows:

arr.uniq!
arr.reject { |ar| arr.select { |another| ar.include? another }.count >= 2 }

Upvotes: 0

Vasfed
Vasfed

Reputation: 18464

Id suggest:

arr.delete_if{|c|
  arr.any? { |s| c != s && c.include?(s) }
}

arr will be modified inplace, so saving memory allocations

Upvotes: 3

Related Questions