Project

General

Profile

Actions

Feature #10208

closed

Passing block to Enumerable#to_h

Added by yhara (Yutaka HARA) over 9 years ago. Updated over 5 years ago.

Status:
Closed
Assignee:
-
Target version:
-
[ruby-core:64808]

Description

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)
    

Related issues 2 (0 open2 closed)

Related to Ruby master - Feature #12512: Import Hash#transform_values and its destructive version from ActiveSupportClosedmatz (Yukihiro Matsumoto)Actions
Has duplicate Ruby master - Feature #15143: Extend `Enumerable#to_h`Closednobu (Nobuyoshi Nakada)Actions
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0