Reputation: 4962
How can I combine these two arrays in to a hash. They may be of equal sizes or not.
@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">]
They are sorted already. I just need the hash to deal with the "blanks" properly like so:
{"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}
Upvotes: 1
Views: 99
Reputation: 29349
You can use zip to merge the arrays into two dimensional and then use the following to convert into hash
Hash[@status_array.zip(@part_milestones)]
Documentation for Hash[]
UPDATE:
just realized that its not a one to one mapping
hash = {}
@status_array.each do |status|
hash[status] = @part_milestone.find{|milestone| milestone.data_type == status}
end
Upvotes: 1
Reputation: 4802
The cleanest way I know to do this is:
hash = @status_array.inject({}) do |result_hash, status|
result_hash[status] = @part_milestones.select { |milestone| milestone.data_type == status }.first
result_hash
end
Upvotes: 1