Reason #101 •
April 11th, 2026
ActiveSupport: Enumerable#index_by
If Enumerable#group_by is for "many values per key", then index_by is for "exactly one value per key". Think of it as applying a unique index to an enumerable:
Ruby
people = [
{ id: 101, email: "[email protected]" },
{ id: 102, email: "[email protected]" },
{ id: 103, email: "[email protected]" }
]
people_by_id = people.index_by { it[:id] }
# => {
# 101 => { id: 101, email: "[email protected]" },
# 102 => { id: 102, email: "[email protected]" },
# 103 => { id: 103, email: "[email protected]" }
# }
people_by_id[102]
# => { id: 102, email: "[email protected]" }
JavaScript
const people = [
{ id: 101, email: "[email protected]" },
{ id: 102, email: "[email protected]" },
{ id: 103, email: "[email protected]" }
];
const peopleById = Object.fromEntries(
people.map((person) => [person.id, person])
);
// => {
// 101: { id: 101, email: "[email protected]" },
// 102: { id: 102, email: "[email protected]" },
// 103: { id: 103, email: "[email protected]" }
// }
peopleById[102];
// => { id: 102, email: "[email protected]" }
Note: If two elements produce the same key, the last one wins.
History
Enumerable#index_by was added to ActiveSupport in Rails 1.2.0, released in 2007.