开发者

Ordering gets lost when data is stored in a hash

I had taken from the d开发者_如何学Goatabase 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?


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


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜