Issue #8490 has been updated by Eregon (Benoit Daloze).


rosenfeld (Rodrigo Rosenfeld Rosas) wrote:
> I'd prefer index_by! to raise an exception instead...

! is not used for exception-raising methods in ruby core and stdlib.

> What if you know that any duplicate would actually map to the same object?

There should be some possibility to merge duplicates like Hash#merge in that case.
But is it worth the complexity? If you need some merging strategy,
the operation is no more mere "indexing", and I would favor the current approach ("h={}; enum.each { |e| h[e.k] = e if ... }").

> Also, you can't judge how my ORM should work (anyway, all the ORM I've worked with, both in Ruby, Groovy and Java have a very similar API when it comes to fetching a list of records, there's nothing special on this regular requirement)...

Well, the ORM (or whatever you use between DB and code) could do this.
And having something like "index = {}; each_record { |record| index[record.key] = record }; index"
could be useful I guess. For instance, Sequel has some Dataset#select_hash which is somewhat similar.

> Sometimes I'm working in something that would take advantage of some caching of records by id that I'll use somewhere, but that doesn't mean I always need to index by id... This was just a use case, it doesn't mean that every time I need to index a list of objects it comes from the database...

Yes, of course. I agree it would be useful to have something like index_by.
But maybe, as in the #cache_fetch example, it would be useful to be able to change/map the values too.
(if the name has "map" in it, it should map values as well.)

> So I can't understand why you're so sure that "I should use a different technique in the code" as you don't even know my code...

I am not "so sure", I started with "I think".
Of course there are special cases and I can not know your code.
But to me using keys like that for databases record does not seem the most appropriate way to do it at first sight (probably best iterating on the properly sorted result set).
----------------------------------------
Feature #8490: Bring ActiveSupport Enumerable#index_by to core
https://bugs.ruby-lang.org/issues/8490#change-39776

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/