[ruby-core:64967] [ruby-trunk - Feature #10208] Passing block to Enumerable#to_h

From: yutakaha.ra@...
Date: 2014-09-11 16:19:37 UTC
List: ruby-core #64967
Issue #10208 has been updated by Yutaka HARA.


Marc-Andre Lafortune wrote:
> I completely agree that we need new methods to do this.

Thanks. One idea is name it Enumerable#hash_by (like max_by, group_by)

~~~
User =3D Struct.new(:id, :name)
users =3D [User.new(1, "Alice"), User.new(2, "Bob")]

users.hash_by{|u| [u.id, u.name]}
# {1 =3D> "Alice", 2 =3D> "Bob"}
~~~




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

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

Example:

~~~
# Convert users into an {id =3D> name} hash
users.map{|u| [u.id, u.name]}.to_h
    =E2=86=93
# Convert users into an {id =3D> 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]}
  =3D=3D 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)
  =3D=3D hsh.to_h{|k, v| [k.to_s, v]}
  hsh.map_v(&:to_i)
  =3D=3D hsh.to_h{|k, v| [k, v.to_i]}
  hsh.map_kv(&block)
  =3D=3D hsh.to_h(&block)




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

In This Thread

Prev Next