Looping through the index of an array
ruby
Solution
the syntax for `each_with_index` is like this:
@something.each_with_index do |thing,index|
puts index, thing
end
You should then replace the line emails.each_with_index do |index|
with
emails.each_with_index do |email,index|
However I don't see you actually using the index so you could probalby simplify it to this:
emails.each do |email|
email.attachments.each do | attachment |
....
Problem
I am working on a Ruby script that will download emails from Gmail and download attachments matching a specific pattern. I am basing this off the excellent Mail gem for Ruby. I am using Ruby 1.9.2. I am not that experienced with Ruby and appreciate any help offered. In the code below, emails is an array of emails returned from gmail that contain a specific label. What I am stuck on is looping through the array of emails and processing what may be multiple attachments on each email. The inner loop of emails[index].attachments.each does work if I specify an index value, I have not been successful in wrapping the first loop to go through all the index values of the array. ``` emails = Mail.find(:order => :asc, :mailbox => 'label') emails.each_with_index do |index| emails[index].attachments.each do | attachment | # Attachments is an AttachmentsList object containing a # number of Part objects if (attachment.filename.start_with?('attachment')) filename = attachment.filename begin File.open(file_dir + filename, "w+b", 0644) {|f| f.write attachment.body.decoded} rescue Exception => e puts "Unable to save data for #{filename} because #{e.message}" end end end end ```