From: sto.mar@... Date: 2012-11-30T15:22:32+09:00 Subject: Re: Ordered Hash (v. 1.8) Am 30.11.2012 07:15, schrieb sto.mar@web.de: > Am 30.11.2012 02:46, schrieb Doug Jolley: >> I am running Ruby v. 1.8.7 and I have installed the orderedhash gem. I >> know that the purpose of orderedhash is to preserve the order of >> creation. However, what I'd really like to do is, after the hash has >> been created, sort it on the key in a manner similar to the way that I >> would sort an array with the sort!() method and then preserve the sorted >> order. Any ideas on how I might accomplish that feat? Thanks for any >> input. >> >> ... doug > > 1. You could use the RBTree gem. > > 2. Iterate through the sorted keys when you need to access elements > in sorted order: > > 1.9.3p194 :001 > hash = {:c => 1, :a => 2, :b => 3} > => {:c=>1, :a=>2, :b=>3} > 1.9.3p194 :002 > sorted_keys = hash.keys.sort > => [:a, :b, :c] > 1.9.3p194 :003 > sorted_keys.each do |key| > 1.9.3p194 :004 > puts "#{key} => #{hash[key]}" > 1.9.3p194 :005?> end > a => 2 > b => 3 > c => 1 > => [:a, :b, :c] correction: in 1.8, when your keys are symbols you need to sort with sorted_keys = hash.keys.sort_by(&:to_s) --