I want to remove duplicates and elements that are substrings of other
elements. Therefore, the above array would become:
[“John”,“Bobby”]
(order doesn’t really matter to me, BTW)
Right now, this is what I’m doing:
def remove_duplicates_and_subsequences(some_array)
result = []
some_array.each_index do |i|
(some_array.length-1).downto 0 do |j|
some_array.delete_at(j) if i != j &&
some_array[i].index(some_array[j])
end
end
return result
end
Is there a better way to do that? I feel like I should be using select
or
reject, but can’t think of a way to do it.
I want to remove duplicates and elements that are substrings of other
elements. Therefore, the above array would become:
[“John”,“Bobby”]
(order doesn’t really matter to me, BTW)
Right now, this is what I’m doing:
def remove_duplicates_and_subsequences(some_array)
result = []
some_array.each_index do |i|
(some_array.length-1).downto 0 do |j|
some_array.delete_at(j) if i != j &&
some_array[i].index(some_array[j])
end
end
return result
end
Is there a better way to do that? I feel like I should be using select
or
reject, but can’t think of a way to do it.
Thanks,
Sammy L.
You tried to use the method uniq?
[1,2,3,4,1,3].uniq => [1,2,3,4]
Is there a better way to do that? I feel like I should be using select or
reject, but can’t think of a way to do it.
Thanks,
Sammy L.
You can use Array.uniq to remove duplicates. For removing words that
are contained in other words, I would sort the array, then for each
string in the array:
good_strings = []
0.upto(good_strings.length - 2) do |i|
good_strings << strings[i] unless strings[i + 1].include?(strings[i])
end
I think there could also be a .map solution but I cant figure it out
right now, .uniq just really seems the most simple and elegant for this
given problem at hand