From: Rick DeNatale Date: 2007-03-02T05:32:04+09:00 Subject: Re: Sorting a Hash On 3/1/07, khaines@enigo.com wrote: > On Fri, 2 Mar 2007, Nasir Khan wrote: > > > One could perhaps overload the []= method and maintain a sorted parallel > > array in the Hash object (this is what I did in my case). > > Works great in some cases, but array's function means that some operations > are very slow. Array is usually one of the fastest classes in Ruby. Of course the real facts come from benchmarking. Another approach would be to modify the code I posted and cache the sorted keys, and use []= to invalidate the cache, then re-sort on the next access. But one has to be careful if we are talking about patching Hash, since if you look at the implementation of Hash you'll find that not all changes go through the []= method. There's a primitive c function called rb_hash_aset which is used by several other methods besides []=. > > I have a class library in IOWA that I extracted some time ago as a > microproject that provides a structure that provides both hashlike and > arraylike access semantics using a linked list with a hash key -> node > index. > > http://rubyforge.org/frs/download.php/12908/LinkedList_0.99.2.9.tar.gz This appears to be doing something different, it appears to be providing some kind of a hybrid of a hash, and an array with set-like behavior as well. Rather than sorting the keys, it gives a sort of the insertion order access which Hal Fulton keeps asking for. But it also has the dequeue methods from array which push/pop/shift/unshift single values, BUT since in this case it uses the value for the key, it also removes any existing element with the value before adding it back. -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/