How to get first 10 items from hash in ruby?

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])}

#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

maybe ther is a simpler method for this, but from the top of my head
i’d do it like this:

hashTable.keys[1…10].each { |key| puts hash[key] }

sorry just reread your post. of course it would be like this:

hashTable.keys[1…10].each { |key| puts “#{key} => #{hash[key]}” }

How about
hashTable.sort.keys[0,10].each { |key| puts "#{key} #{hashTable[key]} }

Christian

Christian van der Leeden wrote:

How about
hashTable.sort.keys[0,10].each { |key| puts "#{key} #{hashTable[key]} }

This isn’t going to work because hashTable.sort does not return a hash.
The object returned does not have a keys method.

However, reversing the chaining will work, and should actually be more
efficient anyway:

Example:
hashTable.keys.sort[0,10].each { |key| puts "#{key} #{hashTable[key]} }

In this case you get the keys array from the hash and then sort the keys
and take the first 10 keys then finally iterate the 10 with each.

P.S. I’m guessing you’re coming from a camelCase world. Which is okay I
live there too as I do Java in my day job. But, if you wish to follow
Ruby conventions your variable should be hash_table not hashTable.