Issue #8490 has been updated by rosenfeld (Rodrigo Rosenfeld Rosas).


Eregon (Benoit Daloze) wrote:
> The name does not indicate clearly what it does (which is chosen if multiple yield the same key) and it is a possibly lossy operation. Can you give a couple examples where it is much better than #group_by?

Sure, suppose you do a database search to fetch some records and you want them mapped by their "id" column. As I said previously, index_by is usually useful when you know beforehand that there should be a single match for the indexed key, like a search in a database table where id is a primary key (uniquely identified). In most ORM solutions that would mean something like:

record_by_id = records.index_by &:id

Since we're not worried about what should happen in case there are multiple matches, we prefer to just use any rule for dealing with those (like using latest match or whatever performs better or is easier to implement). You could also have some index_by! (or map_by!) alternative for raising an exception in case there would be multiple matches if that would be useful for someone to handle that case.

With group_by we'd need to access it like this:

records_by_id = records.group_by &:id
records = records_by_id[id]
record = records && records.first

Just compare to:

record_by_id = records.index_by &:id
record = record_by_id[id]



----------------------------------------
Feature #8490: Bring ActiveSupport Enumerable#index_by to core
https://bugs.ruby-lang.org/issues/8490#change-39729

Author: rosenfeld (Rodrigo Rosenfeld Rosas)
Status: Rejected
Priority: Normal
Assignee: matz (Yukihiro Matsumoto)
Category: core
Target version: 


It seems to be a common sense to have the useful implementation of Enumerable#index_by as in ActiveSupport.

index_by acts like group_by but only maps a single record, instead of an array, keeping the last match only. It's usually used in places where you shouldn't have more than a single match for each key.

Would you consider its inclusion to core Enumerable module?


-- 
http://bugs.ruby-lang.org/