如何将这两个数组合并到一个哈希中。它们的大小可能相同或不同。
@status_array = ["ready", "required", "processing", "approval", "live"]
@part_milestones = [#<Milestone id: 657707, data_type: "ready">, #<Milestone id: 657708, data_type: "required">, #<Milestone id: 657709, data_type: "approval">]
他们已经排序了。我只需要哈希来正确地处理“空白”:
{"ready"=>#<Milestone id: 657707, data_type: "ready">, "required"=>#<Milestone id: 657708, data_type: "required">, "processing"=>nil, "approval"=>#<Milestone id: 657709, data_type: "approval">, "live"=>nil}
答案 0 :(得分:1)
您可以使用zip将数组合并为二维,然后使用以下内容转换为哈希
Hash[@status_array.zip(@part_milestones)]
的文档
<强>更新强>
刚才意识到它不是一对一的映射
hash = {}
@status_array.each do |status|
hash[status] = @part_milestone.find{|milestone| milestone.data_type == status}
end
答案 1 :(得分:1)
我知道这样做最干净的方式是:
hash = @status_array.inject({}) do |result_hash, status|
result_hash[status] = @part_milestones.select { |milestone| milestone.data_type == status }.first
result_hash
end
答案 2 :(得分:-1)
@part_milestones.sort_by &:data_type
应该做的伎俩