无法弄清楚如何只打印此结果的前10行。尝试了一段时间,并且i + = 1方法,但无法适应它。
# make the hash default to 0 so that += will work correctly
from_count = Hash.new(0)
# iterate over the array, counting duplicate entries
results.each do |v|
from_count[v] += 1
end
#prints all k,v values sorted by v but I only want the first 10 lines
from_count.sort_by { |k, v| v }.reverse.each{|k,v| puts "Top 10: \n\n #{v} -- #{k}"}
答案 0 :(得分:1)
非常简单:)
from_count.sort_by { |k, v| v }.reverse.first(10).each{|k,v| puts "Top 10: \n\n #{v} -- #{k}"}
^
答案 1 :(得分:1)
从Ruby 2.2开始,你可以做到
from_count.max_by(10){ |k, v| v }