From: Bob Hutchison Date: 2005-09-26T22:01:26+09:00 Subject: Re: Is there a hash-like class that maintains insertion order Ara, your arrayfield is an excellent fit to what I need. Thanks! The semantics is slightly different (e.g. when you update a field you don't change it's position in the array) than what I had been thinking, but the difference is slight and is perfectly sensible. I've incorporated it into my project (it only took a moment or two) and all the unit tests I had pass. Your alib also looks to be very interesting. Certainly worth looking at just to pick up some Ruby tricks (so is arrayfield for that matter). I'd be more than happy to use it, but I don't know what the license terms are. What are they? Same question for alib. Cheers, Bob On Sep 25, 2005, at 10:34 PM, Ara.T.Howard wrote: > On Mon, 26 Sep 2005, Bob Hutchison wrote: > > > >> Hi, >> >> Is there a Hash-like class that maintains insertion order and, >> ideally, allows 'retrieval' by either key or index? I googled >> around for this but can't seem to hit on a query string that is >> useful. >> >> In a perfect implementation I'd be able to do something like: >> >> hash = HashMaintainingInsertionOrder.new >> hash["a"] = "aaa" >> hash["b"] = "bbb" >> hash["c"] = "ccc" >> >> assert_equal(hash["a"], hash[0]) >> assert_equal(hash["b"], hash[1]) >> assert_equal(hash["c"], hash[2]) >> >> Thanks, >> Bob >> >> ---- >> Bob Hutchison -- blogs at >> Recursive Design Inc. -- >> Raconteur -- >> >> > > harp:~ > cat a.rb > require 'arrayfields' > > a = %w( aaa bbb ccc ) > a.fields = %w( a b c ) > > p a['a'] = a[0] > p a['b'] = a[1] > p a['c'] = a[2] > > > harp:~ > ruby a.rb > "aaa" > "bbb" > "ccc" > > or > > > harp:~ > cat a.rb > require 'arrayfields' > > class HashMaintainingInsertionOrder < ::Array > def initialize > self.fields = [] > end > end > > a = HashMaintainingInsertionOrder::new > > a['a'] = 'aaa' > a['b'] = 'bbb' > a['c'] = 'ccc' > > p a['a'] = a[0] > p a['b'] = a[1] > p a['c'] = a[2] > > harp:~ > ruby a.rb > "aaa" > "bbb" > "ccc" > > this works because assigning to non-existent fields appends a key/ > val pair. > > arrayfields is at > > http://codeforpeople.com/lib/ruby/arrayfields/ > > and cross-listed on the raa. you also may want to check out my > personal lib, > alib, at > > http://codeforpeople.com/lib/ruby/alib/ > > which contains an OrderedHash impl. use like > > require 'alib' > > oh = OrderedHash::new > > but this only returns keys in order for methods like each - it does > not allow > look-up by number __or__ field. > > hth. > > -a > -- > ====================================================================== > ========= > | email :: ara [dot] t [dot] howard [at] noaa [dot] gov > | phone :: 303.497.6469 > | Your life dwells amoung the causes of death > | Like a lamp standing in a strong breeze. --Nagarjuna > ====================================================================== > ========= > > > ---- Bob Hutchison -- blogs at Recursive Design Inc. -- Raconteur --