From: Logan Capaldo Date: 2006-06-14T16:19:46+09:00 Subject: Re: impossible to sort a hash by key? On Jun 14, 2006, at 3:03 AM, Oliver Katzer wrote: > Hi everyone! > > is it impossible to sort a hash by key? > > I have a hash like {"plums"=>3, "bananas"=>4, "apples"=>6} > > And what i want is {"apples" => 6, "bananas" => 4, "plums" => 3} > > Hash#sort returns an array. So i've tried this: > > class Hash > def sort_by_key > array = self.sort > # the array is sorted! > array.inject({}) do |hash, value| > hash[value.first] = value.last > hash > end > end > end > > But the result is {"plums"=>3, "bananas"=>4, "apples"=>6}! > > So - is it impossible to sort a hash by key? > > Oliver. > > -- > Posted via http://www.ruby-forum.com/. > A hash's order is not guaranteed. If you want to display the hash in sorted order you can do something like the following % cat sorted_hash.rb class Hash def each_ordered_by_key keys.sort.each do |key| yield(key, self[key]) end end end str = "{" hash = {"plums"=>3, "bananas"=>4, "apples"=>6} hash.each_ordered_by_key do |key, value| str << "#{key.inspect}=>#{value.inspect}, " end str[-2, 2] = "}" puts str % ruby sorted_hash.rb {"apples"=>6, "bananas"=>4, "plums"=>3}