Topic: Deleting double entries in arrays

Hi!

Is there a method in Ruby to delete double entries in an array? I'm getting an array made of two sub-arrays, but some entries of the second one already exist in the first one.

Thanks!

Genèse d'une expérience de tension liquide douloureusement salvatrice avec le roi des fleurs au théâtre du rêve de Mary le lion dans un univers sphérique expérimental.

Re: Deleting double entries in arrays

http://ruby-doc.org/core/classes/Array.html

There's no method that delete duplicates between different arrays. Of course you would have to make your own.

Re: Deleting double entries in arrays

False!

your_array.flatten! # you will get a one dimensional array
your_array.uniq! # removes all duplicate entries

Last edited by Javix (2010-07-27 11:01:38)

Re: Deleting double entries in arrays

your_array.uniq!

ought to do it.

Re: Deleting double entries in arrays

Javix wrote:

False!

your_array.flatten! # you will get a one dimensional array
your_array.uniq! # removes all duplicate entries

? Then how would you get the original array of arrays back but with duplicates removed? Seems like OP wanted

[["a"], ["a", "b"]] to turn into [["a"], ["b"]]

Obviously you would have to make your own method to do this and not just use flatten and uniq.

Something like

array = [["a"], ["a", "b"]]
array[1].delete_if { |item| array[0].include?(item) }

Last edited by Kentor (2010-07-27 17:47:34)

Re: Deleting double entries in arrays

Kentor wrote:

? Then how would you get the original array of arrays back but with duplicates removed? Seems like OP wanted

[["a"], ["a", "b"]] to turn into [["a"], ["b"]]

Obviously you would have to make your own method to do this and not just use flatten and uniq.

I'm sorry, I should have been more specific. This is not an array of two sub-arrays, it's actually more a concatenation or something, so it's still a one dimension array. The method uniq! works fine, thank you for your answers.

Genèse d'une expérience de tension liquide douloureusement salvatrice avec le roi des fleurs au théâtre du rêve de Mary le lion dans un univers sphérique expérimental.

Re: Deleting double entries in arrays

uniq! updates the array in place, removing duplicates. uniq (without the bang) returns a de-duplicated array without changing the original.

Re: Deleting double entries in arrays

Btw, for future reference, the Ruby API is full of handy information for this sort of thing.  I like http://rubybrain.com/api/ruby-1.8.6/doc/index.html

You don't have to read the whole thing.  But you should definitely read the pages for the core data classes of String, Array and Hash - you'll learn a lot.  It's a small time investment now for a big time saving in the future.

###########################################
#If i've helped you then please recommend me at Working With Rails:
#http://www.workingwithrails.com/person/ … i-williams