I seem to run into this very often. I need to build a Hash from an array using an attribute of each object in the array as the key.
Lets say I need a hash of example uses ActiveRecord objecs keyed by their ids Common way:
ary = [collection of ActiveRecord objects]
hash = ary.inject({}) {|hash, obj| hash[obj.id] = obj }
Another Way:
ary = [collection of ActiveRecord objects]
hash = Hash[*(ary.map {|obj| [obj.id, obj]}).flatten]
Dream Way: I could and might create this myself, but is there anything in Ruby or Rails that will this?
ary = [collection of ActiveRecord objects]
hash = ary.to_hash &:id
#or at least
hash = ary.to_hash {|obj| obj.id}