Issue #10208 has been updated by Tsuyoshi Sawada.


I think the creation of intermediate arrays for each pair is waste of resource. Can we use combination of two methods? For example, something like:

    users.map_keys(&:id).map_values(&:name)

or

    users.map_values(&:name).map_keys(&:id)

Order of application of the two methods `map_keys` and `map_values` should not matter. When only one of them has applied, the return value should be the original receiver with the information added. As soon as both methods have applied, a hash should be returned.

----------------------------------------
Feature #10208: Passing block to Enumerable#to_h
https://bugs.ruby-lang.org/issues/10208#change-48836

* Author: Yutaka HARA
* Status: Open
* Priority: Normal
* Assignee: 
* Category: core
* Target version: current: 2.2.0
----------------------------------------
Now that we can convert 'a list of [key, value] pairs' into a hash with Enumerable#to_h,
how about make it take a block to specify 'how to convert each element intoa [key, value] pair'? 

Example:

~~~
# Convert users into an {id => name} hash
users.map{|u| [u.id, u.name]}.to_h
    вн
# Convert users into an {id => name} hash
users.to_h{|u| [u.id, u.name]}
~~~

This could also be a solution for these feature requests:

* Feature #6669 A method like Hash#map but returns hash

  hsh.apply{|k, v| [k.to_s, v]}
  == hsh.to_h{|k, v| [k.to_s, v]}

* Feature #7793 New methods on Hash
  Feature #9970 Add `Hash#map_keys` and `Hash#map_values`

  hsh.map_k(&:to_s)
  == hsh.to_h{|k, v| [k.to_s, v]}
  hsh.map_v(&:to_i)
  == hsh.to_h{|k, v| [k, v.to_i]}
  hsh.map_kv(&block)
  == hsh.to_h(&block)




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