Chess Mates
Chess Mates

Reputation: 61

How can I more elegantly remove duplicate items across all elements of a Ruby Array?

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?

Upvotes: 6

Views: 688

Answers (1)

mu is too short
mu is too short

Reputation: 434745

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.

Upvotes: 1

Related Questions