Arun Kumar Arun Kumar - 7 months ago 30
Ruby Question

Ruby - Generate an array of hashes from two nested arrays

I have two nested arrays which look like

a = [["Codereview", 72], ["Exercise", 380], ["Prework", 220], ["Retrospective", 36]]
b = [["Codereview", 72], ["Exercise", 335], ["Prework", 118], ["Retrospective", 36]]

You can assume that the length of the arrays is always the same.

I would like to generate an array of hashes from these two nested arrays which should look like

data = [
{ name: "Codereview", total_marks: 72, student_marks: 72 },
{ name: "Exercise", total_marks: 380, student_marks: 335 },
{ name: "Prework", total_marks: 220, student_marks: 118 },
{ name: "Retrospective", total_marks: 36, student_marks: 36 }

I don't have an idea how to go about this. Any help would be appreciated.


This assumes that the length of both arrays is the same and their order matches up (as far as names go).

>{|e| {name: e.first.first, total_marks: e.first.last, student_marks: e.last.last}}

=> [{:name=>"Codereview", :total_marks=>72, :student_marks=>72},
 {:name=>"Exercise", :total_marks=>380, :student_marks=>335},
 {:name=>"Prework", :total_marks=>220, :student_marks=>118},
 {:name=>"Retrospective", :total_marks=>36, :student_marks=>36}]