From: William James Date: 2006-08-22T01:30:06+09:00 Subject: Re: A use case for an ordered hash Phillip Hutchings wrote: > On 8/14/06, Hal Fulton wrote: > > Robert Klemme wrote: > > > Hal Fulton wrote: > > >> > > >> I never use a hash for fast lookup. I use it because it > > >> allows me easily to associate an arbitrary key with a > > >> value. > > > > > > Um... So you're saying that you wouldn't bother if lookups were O(n)? > > > Wow! > > > > I think you mean "wouldn't care"? > > > > Anyway: I'm happy that lookups are fast. But 99% of the time, > > my hashes are small enough that the time savings is probably > > very small in terms of program execution time. > > Unfortunately for you some of us do things that involve searching > through 30,000 sales records to pull out Joe Bob's statistics. > Sometimes you just don't want to do that on the production database, > it just uses far too many resources. Using an ordered hash for one > person's benefit would kill the speed and jack up memory usage. > > I know an ordered associative array (which I think is a better > description of the functionality) would make some things very easy, > but replacing the Hash is not the way to go. > > Something like this would probably sit better, and is still shorter > than the PHP equiv.: > > # a = [['key 1','1'],['key 2', '2'],['key 3',3]].toAssoc > > # a['key 1'] > => 1 > > # p a > => [['key 1','1'],['key 2', '2'],['key 3',3]] # a = ['key 1','1', 'key 2', '2', 'key 3',3].to_assoc => [["key 1", "1"], ["key 2", "2"], ["key 3", 3]] # a.assoc('key 2') => ["key 2", "2"] # a.set 'key 2', 99 => ["key 2", 99] # a => [["key 1", "1"], ["key 2", 99], ["key 3", 3]] class Array def to_assoc f=nil ; partition{f=!f}.transpose end def set k, v (pair = assoc(k)) ? self[ index(pair) ] = [k,v] : push( [k,v] ) end def rm k (pair = assoc( k )) && slice!( index( pair ) ) end end