views:

109

answers:

4

I had taken from the database and sorted it according to the position. Then I had put the necessary datas into a Hash. After putting the data in hash and I printed the hash. But the result is in reverse order. So I want to reverse the hash. How can I do this?

+5  A: 

I think you want an array and not a hash. Hash are really for unordered key-value pairs.

shoebox639
+4  A: 

You should not rely on the order of the items in a Hash:

The order in which you traverse a hash by either key or value may seem arbitrary, and will generally not be in the insertion order.

In Ruby 1.9 the Hash does remember the insertion order, but in Ruby 1.8 and lower it does not. If the order is important to you then you should use a collection that preserves the order of the elements. You could for example look at OrderedHash.

Mark Byers
+1  A: 

It sounds like you need to use something that keeps an order to your key, value pairs, which a hash doesn't do.

Bryan Denny
A: 

You could also form an array of all the hash keys and sort them in which every way you like. Then you can iterate over the array and index the hash with your keys.

Samo