2012-04-15 152 views
3

我正在研究一个Ruby脚本,该脚本将从Gmail下载电子邮件并下载匹配特定模式的附件。我基于Ruby的优秀Mail gem。我正在使用Ruby 1.9.2。我不是那种Ruby经验丰富,并感谢提供的任何帮助。循环访问数组的索引

在下面的代码中,电子邮件是从gmail返回的包含特定标签的电子邮件数组。我所困扰的是循环浏览电子邮件数组并处理每封电子邮件中可能有多个附件。如果我指定一个索引值,电子邮件[index] .attachments.each的内部循环会工作,但我没有成功包装第一个循环以遍历数组的所有索引值。

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 

回答

10

each_with_index语法是这样的:

@something.each_with_index do |thing,index| 
    puts index, thing 
end 

你应该再更换线路 emails.each_with_index办|首页|

emails.each_with_index do |email,index| 

但是我没有看到你实际使用的索引,所以你可以probalby它简化为这样:

emails.each do |email| 
    email.attachments.each do | attachment | 
.... 
+1

啊,简单。我爱Ruby。我想,太多的JavaScript,被附加到使用索引。谢谢@Andreas。 – analyticsPierce 2012-04-16 03:23:10

+0

相同。 js开发者困惑为什么'arr.each do | x,i |'不工作! – 2014-05-13 15:22:49

3

each_with_index产生的第一个参数是对象,而不是索引。

emails.each_with_index do |o, i| 
    o.attachments.each do | attachment | 

,除非你需要,我们还没有看到代码索引,你可以只使用each方法那里。

+0

党,打我给它。 – 2012-04-15 20:00:43