# Create a counter in a hash to return first 10 results only

**URL:** <https://www.ruby-forum.com/t/create-a-counter-in-a-hash-to-return-first-10-results-only/184078>\
**Category:** Ruby\
**Created:** [February 24, 2010, 7:53pm UTC](https://www.ruby-forum.com/t/create-a-counter-in-a-hash-to-return-first-10-results-only/184078 "2010-02-24T19:53:40Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![princenamor](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/c0e974/32.png) [@princenamor](https://www.ruby-forum.com/u/princenamor)\
**Post date:** [February 24, 2010, 7:53pm UTC](https://www.ruby-forum.com/t/create-a-counter-in-a-hash-to-return-first-10-results-only/184078/1 "2010-02-24T19:53:40Z")

</div>

New to ruby…

I created a hash array and everything works fine except I can’t figure  
out how to include a counter to return the first 10 results only.

Thanks John

Here is the code

h = Hash.new  
good\_words.each { |w|  
if h.has\_key?(w)  
h[w] = h[w] + 1  
else  
h[w] = 1  
end  
}

# sort the hash by value, and then print it in this sorted order

h.sort{|a,b| b[1]\<=\>a[1]}.each { |elem|

puts “”#{elem[0]}" has #{elem[1]} occurrences"

}

---

<div class="post-metadata">

**Author:** ![princenamor](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/c0e974/32.png) [@princenamor](https://www.ruby-forum.com/u/princenamor)\
**Post date:** [February 24, 2010, 8:52pm UTC](https://www.ruby-forum.com/t/create-a-counter-in-a-hash-to-return-first-10-results-only/184078/2 "2010-02-24T20:52:42Z")

</div>

John Dale wrote:

> New to ruby…
> 
> I created a hash array and everything works fine except I can’t figure  
> out how to include a counter to return the first 10 results only.
> 
> Thanks John
> 
> Here is the code
> 
> h = Hash.new  
> good\_words.each { |w|  
> if h.has\_key?(w)  
> h[w] = h[w] + 1  
> else  
> h[w] = 1  
> end  
> }
> 
> # sort the hash by value, and then print it in this sorted order
> 
> h.sort{|a,b| b[1]\<=\>a[1]}.each { |elem|
> 
> puts “”#{elem[0]}" has #{elem[1]} occurrences"
> 
> }

referred to an earlier post and figured this out.

Thanks

John

---

<div class="post-metadata">

**Author:** ![princenamor](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/c0e974/32.png) [@princenamor](https://www.ruby-forum.com/u/princenamor)\
**Post date:** [February 24, 2010, 9:51pm UTC](https://www.ruby-forum.com/t/create-a-counter-in-a-hash-to-return-first-10-results-only/184078/3 "2010-02-24T21:51:09Z")

</div>

On 24.02.2010 20:52, John Dale wrote:

> > h = Hash.new  
> > h.sort{|a,b| b[1]\<=\>a[1]}.each { |elem|
> > 
> > ```
> > puts "\"#{elem[0]}\" has #{elem[1]} occurrences"
> > 
> > ```
> > 
> > }
> 
> referred to an earlier post and figured this out.

Like?

h = Hash.new 0  
…  
h[w] += 1  
…

puts h.sort\_by {|w,c| -c}[0,10]

Kind regards

robert
