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/.