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 <http://www.recursive.ca/hutch/> > Recursive Design Inc. -- <http://www.recursive.ca/> > Raconteur -- <http://www.raconteur.info/> 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 ===============================================================================