From: Bertram Scharpf Date: 2009-02-14T01:37:52+09:00 Subject: Re: How to retrive first 10 items from hash in ruby? Hi, Am Freitag, 13. Feb 2009, 23:29:05 +0900 schrieb David A. Black: > On Fri, 13 Feb 2009, Bertram Scharpf wrote: >> >> ary = hashTable.sort { |a,b| a[1]<=>b[1] } >> 10.times { puts "Key: %s ==> %s" % ary.pop } > > I'd still rather walk through the array than have to coordinate the > sort operation and a destructive array operation. > > ary = hash_table.sort {|a,b| b[1] <=> a[1] } > # or sort_by {|a| -a[1]} > 10.times {|i| # ary[i] ... } By the way: This is starting to make fun. I don't know how the internal sort mechanism works, but maybe something like this here would be faster? a = Array.new 200 do rand 0x1000 end h = [] a.each { |x| if h.length < 10 or x > h.first then h.push x h.sort! h.shift if h.length > 10 end } Bertram -- Bertram Scharpf Stuttgart, Deutschland/Germany http://www.bertram-scharpf.de