From: Robert Klemme Date: 2011-06-22T23:06:54+09:00 Subject: Re: How to order a hash based on its keys? On Wed, Jun 22, 2011 at 3:47 PM, Iñaki Baz Castillo wrote: > 2011/6/22 Robert Klemme : >> Well, in that case an Array would be much more efficient.  You just >> need a way to deal with holes, e.g. >> >> prio_data = [] >> >> def prio_data.each_pair >>  each_with_index do |x,i| >>    yield i, x if x >>  end >> end >> >> prio_data[1] = "foo" >> prio_data[4] = "bar" >> >> prio_data.each_pair {|prio,v| printf "key=%p val=%p\n", prio, v} > > Interesting approach :) > > >>> Then I just want to get a new hash in which entries are ordered by >>> priority. >> >> Why do you need a second container object?  Is this just for sorting >> purposes or do you actually need to maintain the state from a given >> point in time? > > The second container (an ordered one) will be passed (later) to a > method which randomizes each DNS result based on its SRV weight. So > first I need a contained in which DNS records are ordered by priority, > and later a randomize method (already done) which shorts the array > entries of each priority value based on entries weight (randomly of > course, but taking into account the weight of each SRV record). > > I've it already working, but I will take a more deepth look to your > above code to integrate it. Hm... Now I am not sure any more whether you need a associative container at all. Now we have three steps. From what I understand you do: 1. items are collected 2. items are ordered by priority (what you call second container above) 3. items are ordered by some randomization algorithm I'm obviously missing other access operations out here. So far I don't see any need for a Hash or similar structure. What else is it that you need to do with these items? What properties do they have? Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/