Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

ruby

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?

like image 520
Chess Mates Avatar asked Oct 11 '14 18:10

Chess Mates


People also ask

How do you remove duplicate values from an array 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.

What does .select do in Ruby?

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.


1 Answers

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.

like image 144
mu is too short Avatar answered Oct 01 '22 03:10

mu is too short