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

J

John Mr.

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"

}
 
J

John Dale

John said:
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
 
R

Robert Klemme

John said:
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.

Like?

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

puts h.sort_by {|w,c| -c}[0,10]

Kind regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top