Issue #7297 has been updated by bitsweat (Jeremy Kemper).


Some background:

#4151 proposes an Enumerable#categorize API, but it's complex and hard to understand its behavior at a glance.
#7292 proposes an Enumerable#to_h == Hash[...] API, but I don't think of association/pairing as explicit coercion, so #to_h feels misfit.

Associate is a simple verb with unsurprising results. It doesn't introduce ambiguous "map" naming. You associate an enumerable of keys with yielded values.

Some before/after examples:

Before: Hash[ filenames.map { |filename| [ filename, download_url(filename) ]}]
After:  filenames.associate { |filename| download_url filename }
# => {"foo.jpg"=>"http://...", ...}

Before: alphabet.each_with_index.each_with_object({}) { |(letter, index), hash| hash[letter] = index }
After:  alphabet.each_with_index.associate
# => {"a"=>0, "b"=>1, "c"=>2, "d"=>3, "e"=>4, "f"=>5, ...}

Before: keys.each_with_object({}) { |k, hash| hash[k] = self[k] }  # a simple Hash#slice
After:  keys.associate { |key| self[key] }

Apologies for hijacking this rejected ticket with a different proposal. I will open a new feature request if anyone is positive on this usage.
----------------------------------------
Feature #7297: map_to alias for each_with_object
https://bugs.ruby-lang.org/issues/7297#change-32593

Author: nathan.f77 (Nathan Broadbent)
Status: Rejected
Priority: Normal
Assignee: 
Category: lib
Target version: 2.0.0


I would love to have a shorter alias for 'each_with_object', and would like to propose 'map_to'. Here are my arguments:

* It reads logically and clearly:

[1, 2, 3].map_to({}) {|i, hash| hash[i] = i ** 2 }
#=> {1 => 1, 2 => 4, 3 => 9}

* Rubyists are already using 'map' to build and return an array, so it should be obvious that 'map_to(object)' can be used to build and return an object.

* Given that 'each' and 'each_with_index' return the original array, I feel that the 'each_with_object' method name is slightly counterintuitive. 'map_to' might not be 100% semantically correct, but it's obvious that it will return something other than the original array.

* Many people (myself included) were using inject({}) {|hash, el| ... ; hash } instead of 'each_with_object', partly because of ignorance, but also because 'each_with_object' is so long. 'map_to' is the same length as inject, and means that you don't have to return the object at the end of the block.

* Only a single line of code is needed to implement the alias.


Best,
Nathan


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