Reputation: 171
Brand new to Ruby. Am trying to sort a de-duplicated list of email FROM (senders) with the # of emails sent. This code is working but it's sorting alphabetically. I can't figure out how to sort it so that most # of emails is on top, etc.
results = []
mail_count = imap.search(["SINCE", @this_week.strftime("%d-%b-%Y")]).each do |message_id|
envelope = imap.fetch(message_id, "ENVELOPE")[0].attr["ENVELOPE"]
@from_array = envelope.from[0].name.to_a
results << @from_array
end
# 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
from_count.sort_by do |k, v| v
puts "#{v} -- #{k}"
end
Upvotes: 1
Views: 250
Reputation: 40533
from_count.sort_by{|k,v| v }
Should do the trick.
You can then iterate over the sorted hash and print the results.
So then your code would look like this:
from_count.sort_by{|k,v| v }.first(10).each{|k,v| puts "#{v} -- #{k}" }
The sort_by
sorts it, then when the sorting is done we print the results.
Upvotes: 1