On 13 Feb 2009, at 11:04, Vikas Gholap wrote:

> Hello All, I am new to programming, i have little problem with hash.
>
> I want to retrieve first 10 items(key value pairs) from given hash{}
>
> hashTable = {"a" => 1, "b" => 5, "c" => 2, "d" => 6, "e" => 4, "f"  
> => 7,
> "g" => 9, "h" => 5, "i" => 1, "j" => 8, "k" => 9, "l" => 3, "m" => 7,
> "n" => 10, "o" => 12}
>
> #sort hashTable on value by descending order
> hashTable.sort {|a,b| -1*(a[1]<=>b[1])}

You need to save the results.
ary = hashTable.sort {|a,b| -1*(a[1]<=>b[1])}

ary is an array of key value pairs stored in an array, i.e. [['o' =>  
12], ['n' => 11], ...]

ary[0, 10] will return an array of the first 10 entries

To print out the first 10 entries:

ary[0, 10].each {|e| puts  "Key: #{e[0} ==> #{[e[1]}"

Dave
>
>
> #now I want 10 items from sorted hashTable
>
> I wrote some thing like
> ---------------------------------
> hashTable.each do |key,value|
>       puts"Key: #{key} ==> #{value}"
>       # I want only first 10
> end
> ------------------------------------
> it prints all elements but i want only 10 items. please help.
>
> Thanks,
> Vikas
> -- 
> Posted via http://www.ruby-forum.com/.
>