Reputation: 2195
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
Reputation: 1281
Another way can be as follows:
arr.uniq!
arr.reject { |ar| arr.select { |another| ar.include? another }.count >= 2 }
Upvotes: 0
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