I want to remove duplicate items within an Array
object. It's best to explain with an example.
I have the following Array
entries = ["a b c", "a b", "c", "c d"]
I want a method which will clean this up by removing duplicate items from within elements in the Array
and return an Array
which has one element for each unique item.
So here's the method I've written to do this:
class Array
def clean_up()
self.join(" ").split(" ").uniq
end
end
So now when I call entries.clean_up
I get the following as a result:
["a", "b", "c", "d"]
This is exactly the result I want but is there a more elegant way to do this in Ruby?
With the uniq method you can remove ALL the duplicate elements from an array. Let's see how it works! Where the number 1 is duplicated. Calling uniq on this array removes the extra ones & returns a NEW array with unique numbers.
Array#select() : select() is a Array class method which returns a new array containing all elements of array for which the given block returns a true value. Return: A new array containing all elements of array for which the given block returns a true value.
split
splits on whitespace by default (assuming of course that you haven't done something insane like changing $;
). You want to split each string and flatten the results into one list, any time you want to "do X to each element and flatten" you want to use flat_map
. Putting those together yields:
self.flat_map(&:split).uniq
If you only want to split on spaces or don't want to depend on sanity, then you could:
self.flat_map { |s| s.split(' ') }.uniq
or similar.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With