From: ara.t.howard@... Date: 2006-10-29T22:34:15+09:00 Subject: Re: keeping a hash' sort order? 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: harp:~ > cat a.rb require 'alib' # rubyforge or raa require 'yaml' oh = alib.orderedhash.new oh['a'] = 1 oh['b'] = 2 oh['c'] = 3 y oh harp:~ > ruby a.rb a: 1 b: 2 c: 3 more examples and explantions abound on the list if you want to google them. -a -- my religion is very simple. my religion is kindness. -- the dalai lama