У меня есть два вложенных массива, которые выглядят как

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

Вы можете предположить, что длина массивов всегда одинакова.

Я хотел бы сгенерировать массив хэшей из этих двух вложенных массивов, которые должны выглядеть как

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 }
]

Я понятия не имею, как это сделать. Любая помощь будет оценена.

0
Arun Kumar Mohan 5 Сен 2016 в 19:37

3 ответа

Лучший ответ

Это предполагает, что длина обоих массивов одинакова, а их порядок совпадает (в части имен).

> a.zip(b).map{|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}]
1
Philip Hallstrom 5 Сен 2016 в 16:48

Простой способ. копирование с консоли

 pry(main)> data =[]
 => []
 3] pry(main)> b_hash =b.to_h
 => {"Codereview"=>72, "Exercise"=>335, "Prework"=>118,Retrospective"=>36}
 pry(main)> a.each do |array|
 [8] pry(main)*   h = Hash.new()
 [8] pry(main)*   h["name"] = array.first
 [8] pry(main)*   h["total_marks"] = array.last
 [8] pry(main)*   h["student_marks"] = b_hash[array.first]
 [8] pry(main)*   data << h
 [8] pry(main)* end
 9] pry(main)> 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}]
0
tessie 5 Сен 2016 в 16:54
a = [["Codereview", 72], ["Exercise", 380], ["Prework", 220], ["Retrospective", 36]]
b = [["Prework", 118], ["Retrospective", 36], ["Codereview", 72], ["Exercise", 335]]

g = a.each_with_object({}) { |(str, val), h| h[str] = { "name"=>str, "total_marks"=>val } }
  #=> {"Codereview"=>{"name"=>"Codereview", "total_marks"=>72},
  #    "Exercise"=>{"name"=>"Exercise", "total_marks"=>380},
  #    "Prework"=>{"name"=>"Prework", "total_marks"=>220},
  #    "Retrospective"=>{"name"=>"Retrospective", "total_marks"=>36}} 
b.each_with_object(g) { |(str, val),h| h[str]["student_marks"] = val }.values
  #=> [{"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}]
0
Cary Swoveland 5 Сен 2016 в 18:51