From: Robert Klemme Date: 2011-06-24T00:13:01+09:00 Subject: Re: How to order a hash based on its keys? On Thu, Jun 23, 2011 at 12:11 AM, Iņaki Baz Castillo wrote: > 2011/6/22 Robert Klemme : >> Aha!  This is how I'd probably do it. >> https://gist.github.com/1040631 > > It's really cool :) Oh, thank you! > I've done it using a different approach, but I think the main > algorithm is similar: > >    pick = rand(@total) >    @items.each_with_index do |it, idx| >      sum += @weight[it] >      return idx if sum > pick >    end > > I do something similar: > >  https://gist.github.com/1041339 > > Note that my code does not use real SRV records for now, but similar > objects (hash/arrays in fact) and I provide it in a specific format (a > hash with SRV priorities as keys). I rather use specific types than Array and Hash since those make the code more readable. Also, this encourages more OOish programs where you distribute functionality across classes. I'd also not use recursion in srv_entries_randomize() - a loop is usually more efficient. And btw. you calculate the total weight every time the method is invoked as sum of all entries while I maintain the @total and adjust it only for every insertion and removal. I notice you have a require 'benchmark' in there but I don't see any Benchmark methods used... You also seem to have the habit of placing assignments in method argument lists or control flow statements. This makes code harder to read and is really only needed in case of loops, e.g. while (str = io.gets) printf "We have read: %p\n", str end There is one thing I don't understand in your code: you have two randomizations in there: in line 8 there is rand() similar to what I have done and in line 34 there is shuffle. Why do you do that? Is there a requirement that hasn't been mentioned yet? > I'm mostly interested in efficience and I'm satisfied with the results > of my code. Well, then that's good. > Thanks a lot. You're welcome! Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/