ruby – 循环遍历数组的索引
发布时间:2020-12-17 01:49:43 所属栏目:百科 来源:网络整理
导读:我正在开发一个 Ruby脚本,它将从Gmail下载电子邮件并下载与特定模式匹配的附件.我基于Ruby的优秀 Mail gem.我使用的是Ruby 1.9.2.我不是那种经验丰富的Ruby,并感谢任何提供的帮助. 在下面的代码中,电子邮件是从gmail返回的包含特定标签的电子邮件数组.我所坚
我正在开发一个
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 解决方法
each_with_index的语法是这样的:
@something.each_with_index do |thing,index| puts index,thing end 然后你应该更换线 同 emails.each_with_index do |email,index| 但是我没有看到你实际使用索引,所以你可以probalby简化它: emails.each do |email| email.attachments.each do | attachment | .... (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |