[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Sorting a Hash

Ara.T.Howard

2/28/2007 9:11:00 PM

3 Answers

khaines

3/1/2007 7:39:00 PM

0

Rick DeNatale

3/1/2007 8:32:00 PM

0

On 3/1/07, khaines@enigo.com <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....

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.denh...

khaines

3/1/2007 9:04:00 PM

0