使用CSV类的奇怪行为

时间:2014-05-14 16:44:04

标签: ruby

以下是这种情况。仅当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中的第一个块之后丢失范围/赋值的原因?

0 个答案:

没有答案