Ruby/Rails:循环访问csv并在找到新人时设置标志的最佳方式

Mar*_*ear 2 ruby csv ruby-on-rails

我觉得这是编程101的东西,但我会吞下我的骄傲并寻求帮助.我有一个我正在处理的CSV.这是一个样本......

person_id, name, start_date
1111, busta, 1/1/14
1111, busta, 1/4/14
1111, busta, 1/7/14
2222, mista, 1/3/14
2222, mista, 1/1/14
2222, mista, 1/11/14
Run Code Online (Sandbox Code Playgroud)

...这是我用来处理行的代码示例...

def self.import(file)
  student_start_dates = Hash.new {|hsh, key| hsh[key] = [] }

CSV.foreach(file.tempfile, :headers => true) do |row|
  student_start_dates[row["person_id"]] << row["start_date"]
  #need something in the loop that says hey...when I find a new person_id send this array to the process method
  end
end

  def self.process(student)
    #process something like 1111 => ["1/1/14", "1/4/14", "1/7/14"]
  end
Run Code Online (Sandbox Code Playgroud)

因此,您可以从数据中看到每个学生都有多个与他们相关的开始日期.我正在尝试为每个学生构建一个start_dates数组.当我找到一个新的person_id时,需要使用我的start_date数组"做一些事情".我的问题是,当我循环遍历csv中的每一行时,添加寻找person_id变化的逻辑的最佳方法是什么?我知道我可以设置某种在person_id更改时设置的标志,然后根据该标志的状态处理我的start_date数组,并重置标志.但是,我试图在没有太多运气的情况下实施.或者当它发生时,感觉"很脏".只是希望一双新鲜的眼睛会给我一些关于清洁代码的想法.

我的问题的很大一部分是设置标志的最佳方式,该标志说"..当你找到一个新学生(new person_id)然后调用过程方法来找到最早的开始日期.

T J*_*T J 5

如果我理解正确的话,你会尝试得到一个看似{1111 => ["1/1/14","1/4/14","1/7/14"]的结果哈希, 2222 => [...],...}

如果是这样,您可以使用内置的CSV解析器,并在循环每一行时构建哈希.

# Create the hash, the default value will be an array
student_start_dates = Hash.new {|hsh, key| hsh[key] = [] }

CSV.foreach(file_name, :headers => true) do |row|
  student_start_dates[row["person_id"]] << row["start_date"]
end
Run Code Online (Sandbox Code Playgroud)