Ruby - 从两个嵌套数组生成一个哈希数组

时间:2016-09-05 16:37:04

标签: ruby

我有两个嵌套数组,看起来像

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

我不知道如何解决这个问题。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:1)

这假设两个数组的长度相同且它们的顺序匹配(就名称而言)。

> 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 :(得分:0)

简单的方法。从控制台

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

答案 2 :(得分:0)

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