Reputation: 561
I have an array of hashes that looks like this:
array= [
{
"id"=> 101,
"first_name"=> "xxx",
"last_name"=> "G",
"email"=> "[email protected]",
"phone_number"=> "555-555-5555"
},
{
"id"=> 102,
"first_name"=> "Jen",
"last_name"=> "P",
"email"=> "[email protected]",
"phone_number"=> "555-555-5555"
}
]
I want to convert it to a hash that looks like this:
array = {
"101"=>
{
"first_name"=> "xxx",
"last_name"=> "G",
"email"=> "[email protected]",
"phone_number"=> "555-555-5555"
},
"102"=>
{
"first_name"=> "Jen",
"last_name"=> "P",
"email"=> "[email protected]",
"phone_number"=> "555-555-5555"
}
}
I have tried this but it does not work:
array.each do |a|
a.map{|x| x[:id]}
end
How can I do this in Ruby? I am looking at the map function, but not sure how to implement it in this case. Please help!
Upvotes: 1
Views: 96
Reputation: 10251
Try this:
array_h = Hash.new
array.each{|a| array_h[a["id"]] = a.reject{|e| e=='id' }}
#Output of array_h:
{
101=>
{
"first_name"=>"xxx",
"last_name"=>"G",
"email"=>"[email protected]",
"phone_number"=>"555-555-5555"
},
102=>
{
"first_name"=>"Jen",
"last_name"=>"P",
"email"=>"[email protected]",
"phone_number"=>"555-555-5555"
}
}
Note: This will not modify your original Array.
Upvotes: 3
Reputation: 44380
This works(desctructive):
>> Hash[array.map { |x| [x.delete("id"), x] }]
=>{
101=>{
"first_name"=>"xxx",
"last_name"=>"G",
"email"=>"[email protected]",
"phone_number"=>"555-555-5555"
},
102=>{
"first_name"=>"Jen",
"last_name"=>"P",
"email"=>"[email protected]",
"phone_number"=>"555-555-5555"
}
}
Upvotes: 3
Reputation: 198486
Non-destructive variant (preserves array
) while removing "id"
:
{}.tap { |h| array.each { |a| nh = a.dup; h[nh.delete('id')] = nh } }
# => {101=>{"first_name"=>"xxx", "last_name"=>"G", "email"=>"[email protected]", "phone_number"=>"555-555-5555"}, 102=>{"first_name"=>"Jen", "last_name"=>"P", "email"=>"[email protected]", "phone_number"=>"555-555-5555"}}
array
# => [{"id"=>101, "first_name"=>"xxx", "last_name"=>"G", "email"=>"[email protected]", "phone_number"=>"555-555-5555"}, {"id"=>102, "first_name"=>"Jen", "last_name"=>"P", "email"=>"[email protected]", "phone_number"=>"555-555-5555"}]
Upvotes: 0