From: Harm Aa Date: 2008-03-11T23:21:11+09:00 Subject: Re: Ordered Collection Peter Hug wrote: > If class X has a method <=>(aX), I can sort an Array containing > instances of X using Array.sort!. > > What I really would like is an array that is always ordered. IOW, I want > the object to be inserted at the correct location inside the array when > the object is added to the array. > > Is there an efficient way to do this? > > Pete One option is to subclass Array and override the methods you use to insert the elements. For example, consider the following: class OrderedArray < Array def []=(index, element) push(element) end def push(element) super(element) self.sort! end end You could even add the code to insert the element in the correct place, but this is a good start. Another option is to use delegation to wrap the Array, and just implement the methods you desire: class OrderedArray < Array def initialize @array = [] end def []=(index, element) push(element) end def [](index) @array[index] end def pop @array.pop end def push(element) @array.push(element) @array.sort! end end With kind Regards, Sam and Harm -- Posted via http://www.ruby-forum.com/.