From: William James Date: 2006-07-26T14:05:12+09:00 Subject: Re: Hash order bug? Hal Fulton wrote: > William James wrote: > > No. What language has ordered hashes? > > > > When you say > > a = {:gr => false, :und => false, :det => true, :sta => false, :inv > > => false} > > you are saying that you want to access the values in this fashion: > > a[:und] > > So the order in which they are stored is irrelevant. > > If you want to access them this way > > a[1] > > then you set them up like this > > [ false, false, true, false, false ] > > > > If you want to get a sequence of values in a certain order: > > a.values_at( :und, :det, :sta ) > > Your point is well taken. David Alan Black also argues eloquently > against the concept of an ordered hash. > > But to me there is psychological weight in seeing a literal of this form: > > {a=>b, c=>d, e=>f} > > There is in fact a syntactic order (which turns out to be meaningless > internally). In awk, such hash literals don't exisit; so when using that language, one is less tempted to imagine that hashes are ordered. Perhaps we should think of the above as 'syntactic sugar' for a = Hash.new; a[a]=b; a[c]=d; a[e]=f > > > If you want to have your cake and eat it too, you could > > use an association list: Lisp also uses these. > > > > > >>>as = [[:foo,22], [:bar,33], [:baz,44]] > > > > => [[:foo, 22], [:bar, 33], [:baz, 44]] > > [snip] > > That works fine, but I dislike the ugly syntax. Maybe this is better. a = [ :foo,22, :bar,33, :baz,44 ].to_assoc a.assoc_set :bar, 99 a.assoc_set :yes, -1 a.assoc_del :baz The prerequisite: class Array def to_assoc f=nil ; partition{f=!f}.transpose end def assoc_set k, v (pair = assoc(k)) ? self[ index(pair) ] = [k,v] : push( [k,v] ) end def assoc_del k (pair = assoc( k )) && slice!( index( pair ) ) end end > > > Hal