Convert array-of-hashes to a hash-of-hashes, indexed by an attribute of the hashes
Ruby <= 2.0
> Hash[api_response.map { |r| [r[:id], r] }]
#=> {1=>{:id=>1, :foo=>"bar"}, 2=>{:id=>2, :foo=>"another bar"}}
However, Hash::[] is pretty ugly and breaks the usual left-to-right OOP flow. That's why Facets proposed Enumerable#mash:
> require 'facets'
> api_response.mash { |r| [r[:id], r] }
#=> {1=>{:id=>1, :foo=>"bar"}, 2=>{:id=>2, :foo=>"another bar"}}
This basic abstraction (convert enumerables to hashes) was asked to be included in Ruby long ago, alas, without luck.
Ruby >= 2.1
[UPDATE] Still no love for Enumerable#mash
, but now we have Array#to_h. Not ideal -because we need an intermediate array- but better than nothing:
> object = api_response.map { |r| [r[:id], r] }.to_h