From: Peter Ertl Date: 2006-06-14T18:59:51+09:00 Subject: Re: impossible to sort a hash by key? > h={:c=> 1, :b=> 2, :a => 3} > a=[] > h.keys.sort_by {|s| s.to_s}.each {|key| puts h[key] } > puts a => [[:a, 3], [:b, 2], [:c, 1]] -------- Original-Nachricht -------- Datum: Wed, 14 Jun 2006 18:48:06 +0900 Von: Paul Battley An: ruby-talk@ruby-lang.org Betreff: Re: impossible to sort a hash by key? > On 14/06/06, Matthew Harris wrote: > > Hashes are unordered, an "ordered hash" is an oxymoron. > > If you need a hash to be ordered, the easiest way is to use an array. > ... > > => [[:a, 1], [:b, 2], [:c, 3], [:d, 4]] > > And you can then use assoc to look up the corresponding element: > > a = [[:a, 1], [:b, 2], [:c, 3], [:d, 4]] > a.assoc(:c)[1] #=> 3 > > The look-up performance for large arrays will be far inferior to that > of a hash, however. > > Paul.