我想加入两个哈希值,比如数据库表,并将它们合并到一个哈希中。 我有两组哈希,如下所示:
哈希1:
classrooms = [{"id"=>4, "title"=>"Class A"}]
哈希2:
teacher_lessons = [{"program_day"=>1, "bell"=>1, "lesson_id"=>1, "classroom_id"=>4},
{"program_day"=>1, "bell"=>2, "lesson_id"=>3, "classroom_id"=>4},
{"program_day"=>2, "bell"=>1, "lesson_id"=>4, "classroom_id"=>4}]
预期:
[{"program_day"=>1, "bell"=>1, "lesson_id"=>1, "classroom_id"=>4, "classroom_title"=> "Class A"},
{"program_day"=>1, "bell"=>2, "lesson_id"=>3, "classroom_id"=>4, "classroom_title"=> "Class A"},
{"program_day"=>2, "bell"=>1, "lesson_id"=>4, "classroom_id"=>4, "classroom_title"=> "Class A"}]
答案 0 :(得分:4)
假设你有很多教室,我会先改变教室数据:
classrooms = [{"id" => 4, "title" => "Class A"},
{"id" => 5, "title" => "Class B"}]
title_by_id = classrooms.map(&:values).to_h
#=> {4=>"Class A", 5=>"Class B"}
然后根据“classroom_id”键简单地修改每个哈希:
teacher_lessons.each {|hash| hash["title"] = title_by_id[hash["classroom_id"]]}
#=>[{"program_day"=>1,"bell"=>1,"lesson_id"=>1,"classroom_id"=>4,"title"=>"Class A"},
# {"program_day"=>1,"bell"=>2,"lesson_id"=>3,"classroom_id"=>4,"title"=>"Class A"},
# {"program_day"=>2,"bell"=>1,"lesson_id"=>4,"classroom_id"=>4,"title"=>"Class A"}]
如果您不想修改源对象,请使用map
+ merge
:
teacher_lessons.map {|h| h.merge("title" => title_by_id[h["classroom_id"]])}