Rails从csv构建嵌套数组

时间:2014-03-03 14:51:33

标签: ruby-on-rails arrays csv

周一早上快乐!

我正在构建一个将要处理CSV的rails应用。目前我在我的模式中有这个...

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

    CSV.foreach(file.tempfile, :headers => true) do |row|
      #student[row["person_id"]] << row["start_date"]
      student_start_dates[row["person_id"]] << row["start_date"]
      student_end_dates[row["person_id"]] << row["end_date"]
      student_last_attend_dates[row["person_id"]] << row["last_attend_date"]
      student_final_grades[row["person_id"]] << row["final_grade"]
    end

...这给了我看起来像......

的数组

end_dates

{"1159821"=>["8/19/2013", "8/19/2013", "8/19/2013", "8/27/2013", "8/19/2013", "8/19/2013", "8/19/2013"], "709267"=>["8/19/2013", "8/19/2013", "8/19/2013", "8/19/2013"], "1103305"=>["8/19/2013", "8/19/2013", "8/19/2013", "8/19/2013"]}

start_dates

{"1159821"=>["12/14/2013", "12/14/2013", "12/14/2013", "12/14/2013", "12/14/2013", "12/14/2013", "12/14/2013"], "709267"=>["12/14/2013", "12/14/2013", "12/14/2013", "12/14/2013"]}

我需要的东西看起来像......

{"1159821"=>"start_dates"=>["8/19/2013", "8/19/2013", "8/19/2013", "8/27/2013", "8/19/2013", "8/19/2013", "8/19/2013"], "end_dates"=>["8/19/2013", "8/19/2013", "8/19/2013", "8/19/2013"], "1103305"=>["8/19/2013", "8/19/2013", "8/19/2013", "8/19/2013"]}

因此,每个学生的数据都封装在一个我可以为每个学生处理的单个数组中。

1 个答案:

答案 0 :(得分:1)

以下内容将为学生创建一个我认为您应该可以使用的数据哈希值。即{“student_id1”=&gt; id1_data,“student_id2”=&gt; id2_data}

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

  CSV.foreach(file.tempfile, :headers => true) do |row|
    students[row["person_id"]]["start_dates"] << row["start_date"]
    students[row["person_id"]]["end_dates"] << row["end_date"]
    students[row["person_id"]]["last_attend_dates"] << row["last_attend_date"]
    students[row["person_id"]]["final_grades"] << row["final_grade"]
  end
  students
end