2016-03-07 36 views
2

我是新来的Ruby的一列,所以道歉,如果这是死容易:-)红宝石 - 比较相邻项的CSV文件

我有5列的.csv文件。第一列有一个记录标识符(在这种情况下是一个驱动程序编号),每行的其他4列都有与该记录相关的数据。对于每个记录,大约有50行数据(总共只有2000行)。 .csv文件有一个标题行。

我需要读取.csv文件并确定每个用户的最后一个条目,以便我可以转到下一个用户。我试图让它比较第一列和下一行中的条目。

我有这个到目前为止,它返回不正确的行号,他们在1到5行之间的任何地方......?!?!

require 'csv-mapper' 

    Given(/^I compare the driver numbers from rows "(.*?)" to "(.*?)"$/) do |firstrow, lastrow| 
    data = CsvMapper.import('C:/auto_test_data/Courts code example csv.csv', headers: true) do 
     [dln] 
    end 

    row = firstrow.to_i 
    while row <= lastrow.to_i 
     @licnum1 = data.at(row).dln 
     @licnum2 = data.at(row+1).dln 

     if 
     @licnum2 == @licnum1 
      $newrecord = "same" 
     else 
     $newrecord = @licnum2 
     end 

     if 
     $newrecord != "same" 
     puts "Last row for #{@licnum1} is #{row}\n" 
     end 

     row = row + 1 
    end 
    end 

这是.csv文件的布局:

recordidentifier1 dataitem1 dataitem2 code descriptionforcomparison 
recordidentifier1 dataitem1 dataitem2 code descriptionforcomparison 
recordidentifier2 dataitem1 dataitem2 code descriptionforcomparison 
recordidentifier2 dataitem1 dataitem2 code descriptionforcomparison 

所有帮助将不胜感激。

感谢,

彼得

回答

0

这里有一个办法做到这一点

current_identifier = nil 

(firstrow.to_i..lastrow.to_i).each do |row| 

    if current_identifer != data.at(row).dln # current row is new identifier 
    if current_identifier # this is not the first row 
     puts "Last row for #{current_identifier} is #{row-1}\n" 
    end 
    current_identifier = data.at(row).dln # remember current row 
    end 

    # we need to track the last row as the last for the current identifier 
    puts "Last row for #{current_identifier} is #{lastrow.to_i}\n" 
+0

谢谢,先生们:-)干杯整理的问题,@peter。 – Peter

+0

我到了那里。 – Peter