Project

General

Profile

Actions

Feature #6669

closed

A method like Hash#map but returns hash

Added by yhara (Yutaka HARA) over 12 years ago. Updated about 3 years ago.

Status:
Closed
Target version:
-
[ruby-core:45960]

Description

Given a hash h, h.map returns an array(alist), but sometimes I hope it returned a hash.

Example:

class Hash
  def apply(&block)
    self.inject({}) do |h, (k, v)|
      new_k, new_v = *block.call(k, v)
      h[new_k] = new_v
      h
    end
  end
end

score = {
  taro: [1,3,2],
  jiro: [3,5,8,4],
  saburo: [2,9]
}
max_score = score.apply{|k,v| [k, v.max]}
#=> {taro: 3, jiro: 8, saburo: 9}
p max_score[:taro]
#=> 3

I'm not thinking "apply" is a perfect name for this. Maybe "hash_map" is better
(we already have "flat_map").


Files

6669.pdf (41.7 KB) 6669.pdf 1-page presentation slide for the feature request meeting ([ruby-dev:45708]) yhara (Yutaka HARA), 06/30/2012 02:27 AM

Related issues 4 (0 open4 closed)

Related to Ruby master - Feature #4151: Enumerable#categorizeRejectedakr (Akira Tanaka)Actions
Related to Ruby master - Feature #7292: Enumerable#to_hClosedmarcandre (Marc-Andre Lafortune)11/07/2012Actions
Related to Ruby master - Feature #7793: New methods on HashClosedmatz (Yukihiro Matsumoto)Actions
Related to Ruby master - Feature #12512: Import Hash#transform_values and its destructive version from ActiveSupportClosedmatz (Yukihiro Matsumoto)Actions
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0