Arun Kumar Arun Kumar - 1 year ago 62
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.

Answer Source

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}]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download