Issue #10208 has been updated by Akinori MUSHA.


I like this proposal.  I think it is reasonable for `to_h` to take an optional block to specify how to make a hash from a given enumerable object because most enumerable objects are not composed of two element arrays. (IIRC that was the reason why Matz didn't like the idea of adding the method when it was first proposed)

The said use case `users.map{|u| [u.id, u.name]}.to_h` is only as effective as `Hash[users.map{|u| [u.id, u.name]}]`, and that spoils the usefulness of the method defined in Enumerable.  `users.lazy.map{|u| [u.id, u.name]}.to_h` may be cool in that it does not create an intermediate array object, but it still creates a couple of chained lazy enumerable objects and looks far from being concise and straightforward.

What do you guys think?  I don't think we need a new name for this.

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

* Author: Yutaka HARA
* Status: Open
* Priority: Normal
* Assignee: 
----------------------------------------
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 into a [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/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>