… or alternatively an Array which prevents duplicate entries.
Is there some kind of object in Ruby which:
- responds to [], []= and <<
- silently drops duplicate entries
- is Enumerable (or at least supports find_all)
- preserves the order in which entries were inserted
?
As far as I can tell, an Array supports points 1, 3 and 4; while a Set supports 1, 2 and 3 (but not 4). And a SortedSet won’t do, because my entries don’t implement <=>.
There isn’t one as far as I know, and Set by its mathematical nature is meant to be unordered (or at least, implementationally, meant not to guarantee order – in fact its usually implemented as a hash table so it does mess up order).
However, it’s not hard to either extend array directly or subclass it to do this. I just tried it out and this works:
Seems to cover all the bases. I used OReilly’s handy Ruby Cookbook as a reference – they have a recipe for “Making sure a sorted array stays sorted” which is similar.