我正在研究一个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
啊,简单。我爱Ruby。我想,太多的JavaScript,被附加到使用索引。谢谢@Andreas。 – analyticsPierce 2012-04-16 03:23:10
相同。 js开发者困惑为什么'arr.each do | x,i |'不工作! – 2014-05-13 15:22:49