2017-02-24 127 views
0

我需要做的哈希值的數組中的哈希裏面,像這樣:RUBY - 做哈希陣列哈希內的正確方法

merit_hash => { 
    students => [ 
    { 
     "id": id, 
     "name": name, 
     subjects => [ 
      { 
       "id": id, 
       "grade": grade 
      }, 
      { 
       "id": id, 
       "grade": grade 
      } 
     ] 
    }, 
    { 
     "id": id, 
     "name": name, 
     subjects => [ 
      { 
       "id": id, 
       "grade": grade 
      }, 
      { 
       "id": id, 
       "grade": grade 
      } 
     ] 
    } 
    ] 
} 

現在,我只是有學生哈希值的數組,但我不知道要怎麼把主題排列在它的內部,IM這樣做:

merit = {} 
merit["students"] = [] 

students.each do |students| 
    student_subjects = Array.new 
    merit["students"].push( 
     { 
     "id" => students.id, 
     "name" => students.name.to_s 
     selected_batch_subjects.each do |subjects| 
      grade = FinalGrades.where(batch_subject_id:subjects.id, period_id: period.id, student_id: student.id).first.value 
      student_subjects.push(
       { 
      "id" => subjects.id, 
      "grade"=> grade 
       } 
      ) 
     end 
     } 
    ) 
end 

但引發此錯誤

意外「}」 ,期待keyword_end

當我嘗試關閉學生哈希...我能做些什麼來完成這項工作?或者,實現這個最好的方法是什麼?

謝謝!

回答

1

像這樣的東西應該工作:

merit = {} 
merit["students"] = [] 
students.each do |student| 
    student_information = {"id" => student.id, "name" => student.name.to_s} 
    student_subjects = [] 
    selected_batch_subjects.each do |subjects| 
    grade = FinalGrades.where(batch_subject_id:subjects.id, period_id: period.id, student_id: student.id).first.value 
    student_subjects.push({"id" => subjects.id, "grade" => grade}) 
    end 
    student_information[:subjects] = student_subjects 
    merit["students"].push(student_information) 
end 

的重要組成部分,將每個學生的科目已經存在的哈希值。

+0

完美!這是我正在尋找的。非常感謝。 – Hook

1

你的迭代是不是對我很清楚,但對電流環和陣推,你可以這樣做:

merit = {} 
merit["students"] = [] 

students.each do |students| 
    student_subjects = [] 
    merit["students"] << { 
     "id" => students.id, 
     "name" => students.name.to_s 
    } 
    selected_batch_subjects.each do |subjects| 
    grade = FinalGrades.where(batch_subject_id:subjects.id, period_id: period.id, student_id: student.id).first.value 
     student_subjects << {"id" => subjects.id,"grade"=> grade} 
    end 
end