ara.t.howard / noaa.gov wrote:
> On Sun, 29 Oct 2006, dc wrote:
>
> > hi -
> >
> > sure this is a common question...
> > i have a hash of stuff that i want to load/keep in a particular order.
> >
> > irb(main):005:0> hsh =  { "one" => 1, "two" => 2, "three" => 3,
> > "four"=>4, "twentythree"=>23 }
> >
> > gives back:
> > => {"three"=>3, "two"=>2, "twentythree"=>23, "one"=>1, "four"=>4}
> >
> > ruby sorts the hash in apparent random order (by object id?)
>
>
> if you really want to sort on arbitrary keys use an rbtree:
>
>      harp:~ > cat a.rb
>      require 'rbtree' # rubyforge or raa
>
>      rb = RBTree.new
>
>      class Key < ::String
>        attr 'arbitrary'
>        def initialize value, arbitrary
>          super value
>          @arbitrary = arbitrary
>        end
>        def <=> other
>          self.arbitrary <=> other.arbitrary
>        end
>      end
>      def Key(*a, &b) Key.new(*a, &b) end
>
>      rb[ Key("a", 3) ] = 1
>      rb[ Key("b", 2) ] = 2
>      rb[ Key("c", 1) ] = 3
>
>      rb.each{|k,v| p [k,v]}
>
>
>
>      harp:~ > ruby a.rb
>      ["a", 1]
>      ["b", 2]
>      ["c", 3]
>
>
>
> if you want to sort on insertion order use an ordered hash:

Facets' Dictionary class can handle arbitray order via #insert(i,k,v),
as well as automatic sort orders (though it is not as fast as rbtree).

T.