From: Todd Benson Date: 2008-03-30T22:47:12+09:00 Subject: Re: Help on best way to gather/sort results ? On Sat, Mar 29, 2008 at 8:45 PM, Tony De wrote: > > Todd Benson wrote: > > On Sat, Mar 29, 2008 at 1:55 AM, Tony De wrote: > >> > >> Oooooooo! We'll that makes perfect sense. Thanks! You know, sometimes > >> you read your handy pickaxe or a blog somewhere, buy it slides right > >> past you. I appreciate the clarification. > >> > >> tonyd > > > > They all work. I use #sort_by all the time for legibility, and I > > don't care that much about speed for the stuff I work on. According > > to the docs, sort_by doesn't scale by speed for small key sets and > > large populations (that might be your case). It does, however, > > perform better when there occurs object creation for the comparison > > test. > > > > Todd > > Thanks Jesus & Todd for your posts also. I appreciate the education. > Forums are great for getting real world experience on language usage and > gotcha's. So I do have another question on my sort. I realize that in > addition to the sort on the second element in each row of my array > (sourceip) I would also like to then sort on the third element (email). > So my current sort is: > > > @results.sort! {|x, y| y[1] <=> x[1]} > > So this now sorts first by element[2] and then by element[3]: > new_results = @results.sort_by { |x| [x[1], x[2]] } > > There are so many ways to accomplish the same result. That dosen't > mean, however, it's the most efficient. Would there be a more efficient > way to do this? Not that this script is costing me a great deal in > resources. But it nice to code tight when possible. Thanks again. > > > > tonyd On my machine... a = [[3, 2, 1], [4, 5, 6], [1, 5, 7], [1, 2, 3]] t = Time.now 10_000.times do a.sort_by {|x| [x[1], x[2]]} end puts Time.now - t t = Time.now 10_000.times do a.sort {|x,y| [x[1], x[2]] <=> [y[1], y[2]]} end puts Time.now - t 10_000.times do a.sort! {|x,y| [x[1], x[2]] <=> [y[1], y[2]]} end puts Time.now - t => 0.25 #sort_by => 0.453 #sort => 0.859 #sort! This may be due to the creation of addition Array objects within the block. Just a guess. Todd