Forum: Ruby on Rails How to get first 10 items from hash in ruby?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Vikas G. (Guest)
on 2009-02-13 13:45
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
it prints all elements but i want only 10 items. please help.

MaD (Guest)
on 2009-02-13 14:09
(Received via mailing list)
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] }
MaD (Guest)
on 2009-02-13 14:11
(Received via mailing list)
sorry just reread your post. of course it would be like this:

  hashTable.keys[1..10].each { |key| puts "#{key} => #{hash[key]}" }
Christian van der Leeden (Guest)
on 2009-02-13 16:13
(Received via mailing list)
How about
hashTable.sort.keys[0,10].each { |key| puts "#{key} #{hashTable[key]} }

Robert W. (Guest)
on 2009-02-13 18:48
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:

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.
This topic is locked and can not be replied to.