Posted about 11 years ago. Visible to the public.

Collect a Hash from an Array

Often the built-in group_by Archive and index_by Archive methods will do the trick.

Since Ruby 2.1 you can use to_h to create a Hash by mapping over an array:

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

Since Ruby 1.9 Hashes maintain the insertion order of their keys and values.

Legacy solution: collect_hash monkey patch

The attached initializer will let you create a hash from an array in a single method call.

  • Copy the attached initializer to config/initializers
  • All enumerables (arrays, sets, scopes, etc.) now have an additional method collect_hash
  • The method takes a block. The block is called for each element in the array and should return a 2-tuple where the first element is the key and the second element is the value.
  • A key/value entry is skipped when the block returns nil.


The following will turn a list of User records into a hash where the keys are the users' ids and the values are the users' attribute hashes:

users = User.all user_plans = users.collect_hash do |u| [, u.attributes] end

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Henning Koch
Last edit:
over 1 year ago
by Henning Koch
list, map
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more