Is there a good way in ruby to remove duplicates in enumerable lists (i.e. reject, etc.)
Asked
Active
Viewed 2,992 times
5
-
Can you specify what kind of list you have in mind that (1) *isn't* an array but (2) could possibly have duplicates? Ranges can't have duplicates. – Telemachus Sep 06 '09 at 19:17
-
"enumerable lists" is very unclear. Is it a instance variable of Enumerator class? – peterpengnz Dec 03 '12 at 21:12
4 Answers
10
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.

Jirapong
- 24,074
- 10
- 54
- 72
-
1Note that `(1..10).to_a.uniq` could never be anything but wasted typing since by definition ranges can't have duplicate elements. (Or is there something I'm very confused about?) – Telemachus Sep 06 '09 at 19:13
-
You're right, it is never duplicate. just give an idea. i added another sample, thanks. – Jirapong Sep 07 '09 at 00:27
-
2It's technically possible for a range (of something other than Fixnums) to produce duplicate elements — all it requires is that for some object x, x.succ == x. For example, a class representing Fibonacci numbers would have this property for the number 1. I'm not sure why you would do that — most likely it's a sign of insanity — but it's *possible*. – Chuck Sep 07 '09 at 00:43
2
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"

ennuikiller
- 46,381
- 14
- 112
- 137
-
1I am also confused by "enumerable list". If it is an array, then it's really easy. If it is Enumerator class, then it requires a lot more thinking. – peterpengnz Dec 03 '12 at 21:10
2
You can do a conversion to a Set, if element order is not important.

Blake Pettersson
- 8,927
- 3
- 27
- 36
1
I like using the set logic operators, if the object doesn't have a .uniq method.
a = [2,3,3,5,5,5,6] # => [2, 3, 3, 5, 5, 5, 6]
a | a # => [2, 3, 5, 6]

acsmith
- 1,466
- 11
- 16