Is there a good way in ruby to remove duplicates in enumerable lists (i.e. reject, etc.)
+1
A:
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
2009-09-06 14:00:50
+2
A:
You can do a conversion to a Set, if element order is not important.
Blake Pettersson
2009-09-06 14:15:59
+5
A:
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
2009-09-06 15:25:26
Note 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
2009-09-06 19:13:34
You're right, it is never duplicate. just give an idea. i added another sample, thanks.
Jirapong
2009-09-07 00:27:08
It'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
2009-09-07 00:43:30
@Chuck: Fair enough for the edge cases, but I stand by the main point...
Telemachus
2009-09-07 00:59:02