shorter: > h={:c=> 1, :b=> 2, :a => 3} > h.keys.sort_by {|s| s.to_s}.map {|key| [key, h[key]] } -------- Original-Nachricht -------- Datum: Wed, 14 Jun 2006 18:48:06 +0900 Von: Paul Battley <pbattley / gmail.com> An: ruby-talk / ruby-lang.org Betreff: Re: impossible to sort a hash by key? > On 14/06/06, Matthew Harris <shugotenshi / gmail.com> 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.