Search code examples
rubyarraysalphabetical

sort alphabetically an imap.fetch in ruby


I'm trying to use Ruby's IMAP library to get a list of all the senders of email (the "from") and then sort it alphabetically, and then count how many emails from each person.

I'm getting hung up on step 1 - sorting alphabetically. This is the code I have and it returns a list of all the "from" values, but they are definitely not alphabetical.

Complete ruby novice here-- less than 1 week so pls be gentle.

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
sorted_from = from_array.sort 
puts "#{sorted_from}"
end

Solution

  • Maybe this:

    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
    results.sort.each do |el|
      puts "#{el}"
    end