以下是这种情况。仅当report
是最后一个时才需要生成index
。这就是为什么我有csvsize = []; contents.each{|x| csvsize<<x }; @csvsize = (csvsize.size-1)
。
问题是each_with_index
块不会像此处所示那样触发。 示例1
contents = CSV.open "event_attendees.csv", headers: true, header_converters: :symbol
csvsize = []; contents.each{|x| csvsize<<x }; @csvsize = (csvsize.size-1)
contents.each_with_index do |row, index|
id = row[:_]
name = row[:first_name].downcase.split.map(&:capitalize).join(" ")
phone = clean_phone(row[:homephone])
# . . .
# Generate report from ERB template
report = ERB.new(File.read 'templates/reports.erb').result(binding)
save_to_template({id: 1, directory: 'reports', file: 'report', data: report}) if index == @csvsize
end
如果我像这样重新分配contents
,它将仅触发 :示例2
contents = CSV.open "event_attendees.csv", headers: true, header_converters: :symbol
csvsize = []; contents.each{|x| csvsize<<x }; @csvsize = (csvsize.size-1)
contents = CSV.open "event_attendees.csv", headers: true, header_converters: :symbol
contents.each_with_index do |row, index|
id = row[:_]
name = row[:first_name].downcase.split.map(&:capitalize).join(" ")
phone = clean_phone(row[:homephone])
# . . .
# Generate report from ERB template
report = ERB.new(File.read 'templates/reports.erb').result(binding)
save_to_template({id: 1, directory: 'reports', file: 'report', data: report}) if index == @csvsize
end
为什么需要重新分配存储在contents
中的CSV对象?我必须做contents = CSV.open "event_attendees.csv", headers: true, header_converters: :symbol
两次才感到奇怪,因为我想在运行第二个块之前得到它size
。
有人可以解释为什么或contents
在上面的示例1中的第一个块之后丢失范围/赋值的原因?