Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby removing duplicates in enumerable lists

Is there a good way in ruby to remove duplicates in enumerable lists (i.e. reject, etc.)

like image 536
Daniel Avatar asked Sep 06 '09 13:09

Daniel


3 Answers

For array you can use uniq() method

a = [ "a", "a", "b", "b", "c" ]
a.uniq   #=> ["a", "b", "c"]

so if you just

(1..10).to_a.uniq

or

%w{ant bat cat ant}.to_a.uniq

because anyway almost every methods you do implement will return as an Array class.

like image 61
Jirapong Avatar answered Oct 17 '22 22:10

Jirapong


Well the strategy would be to convert them to arrays and remove the duplicates from the arrays. By the way lists are arrays in ruby in any case so I'm not sure what you mean by "enumerable lists"

like image 35
ennuikiller Avatar answered Oct 17 '22 21:10

ennuikiller


You can do a conversion to a Set, if element order is not important.

http://www.ruby-doc.org/core/classes/Set.html

like image 32
Blake Pettersson Avatar answered Oct 17 '22 20:10

Blake Pettersson