Convert Array of objects to Hash with a field as the key

ruby, type-conversion

Solution

users_by_id = User.all.map { |user| [user.id, user] }.to_h

If you are using Rails, ActiveSupport provides Enumerable#index_by:

users_by_id = User.all.index_by(&:id)

Problem

I have an Array of objects: ``` [ #<User id: 1, name: "Kostas">, #<User id: 2, name: "Moufa">, ... ] ``` And I want to convert this into an Hash with the `id` as the keys and the objects as the values. Right now I do it like so but I know there is a better way: ``` users = User.all.reduce({}) do |hash, user| hash[user.id] = user hash end ``` The expected output: ``` { 1 => #<User id: 1, name: "Kostas">, 2 => #<User id: 2, name: "Moufa">, ... } ```

Original source