Ruby 循环遍历数组的索引
我正在开发一个Ruby脚本,可以从Gmail下载电子邮件,并下载符合特定模式的附件。我是基于对Ruby的极好理解。我正在使用Ruby 1.9.2。我对Ruby不是很有经验,非常感谢您提供的任何帮助 在下面的代码中,电子邮件是gmail返回的包含特定标签的电子邮件数组。我所坚持的是在一系列电子邮件中循环,并处理每封电子邮件上可能有多个附件的内容。电子邮件[index].attachments的内部循环。每个循环都有效。如果我指定了一个索引值,则无法成功包装第一个循环以遍历数组的所有索引值Ruby 循环遍历数组的索引,ruby,Ruby,我正在开发一个Ruby脚本,可以从Gmail下载电子邮件,并下载符合特定模式的附件。我是基于对Ruby的极好理解。我正在使用Ruby 1.9.2。我对Ruby不是很有经验,非常感谢您提供的任何帮助 在下面的代码中,电子邮件是gmail返回的包含特定标签的电子邮件数组。我所坚持的是在一系列电子邮件中循环,并处理每封电子邮件上可能有多个附件的内容。电子邮件[index].attachments的内部循环。每个循环都有效。如果我指定了一个索引值,则无法成功包装第一个循环以遍历数组的所有索引值 emai
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
每个带索引的_产生给块的第一个参数是对象,而不是索引
emails.each_with_index do |o, i|
o.attachments.each do | attachment |
除非您需要我们没有看到的代码中的索引,否则您可以使用那里的
each
方法。带有索引的each的语法如下所示:
@something.each_with_index do |thing,index|
puts index, thing
end
然后,您应该更换该线路
email.each_与_索引do|索引|
与
但是,我没有看到您实际使用索引,因此您可以将其简化为:
emails.each do |email|
email.attachments.each do | attachment |
....
啊,简单。我喜欢鲁比。我想,使用索引时附加了太多javascript。谢谢@Andreas.same。js开发者弄不明白为什么arr.each do | x,i |
不起作用!
emails.each do |email|
email.attachments.each do | attachment |
....