From: "David A. Black" Date: 2009-02-14T00:21:08+09:00 Subject: Re: How to retrive first 10 items from hash in ruby? Hi -- On Sat, 14 Feb 2009, Robert Klemme wrote: > 2009/2/13 Bertram Scharpf : >> Hi, >> >> Am Freitag, 13. Feb 2009, 22:02:31 +0900 schrieb David A. Black: >>> On Fri, 13 Feb 2009, Bertram Scharpf wrote: >>>> Am Freitag, 13. Feb 2009, 21:08:19 +0900 schrieb Dave Baldwin: >>>>> On 13 Feb 2009, at 11:04, Vikas Gholap wrote: >>>>> >>>>>> I want to retrieve first 10 items(key value pairs) from given hash{} >>>>>> >>>>> ary = hashTable.sort {|a,b| -1*(a[1]<=>b[1])} >>>>> >>>> As ary is only of temporary use, you don't need to create another >>>> array ary[0,10]. I suggest: >>>> >>>> 10.times { puts "Key: %s ==> %s" % e.shift } >>> >>> Do you mean ary.shift? >> >> Arrgh. Of course. >> >> The code may still be improved: Omit the multiplication by -1 in >> the sort block. >> >> ary = hashTable.sort { |a,b| a[1]<=>b[1] } >> 10.times { puts "Key: %s ==> %s" % ary.pop } > > Did we have these already? > > p hash_table.sort_by {|k,v| -v}.first(10) > p hash_table.sort_by {|k,v| v}.last(10).reverse I think the original split between the sort and the puts was because the main question was about sort, and the puts was just to examine the results. David -- David A. Black / Ruby Power and Light, LLC Ruby/Rails consulting & training: http://www.rubypal.com Coming in 2009: The Well-Grounded Rubyist (http://manning.com/black2) http://www.wishsight.com => Independent, social wishlist management!