Editing Topic: RCR278 Project: RCR | RCRchive home

RCR 278: Hash#collect_to_hash method

submitted by Zallus on Sat Sep 11 2004 10:02:28 PM -0700

Status: pending


Abstract

A simple method for Hashes (or Mappables), like #collect, but that returns a Hash, mapping the old keys to the returned values.

Problem

I often run into the problem of having a hash, and needing a new, modified hash. Enumerable#collect works as a "filter" method well enough when you are dealing with Arrays, but Hash#collect, suprisingly, also returns an Array. This usually leads to the following code:
newHash = Hash.new
oldHash.each { |k,v| newHash[k] = modify_in_some_way(v) }
newHash
Or, at the very least:
oldHash.keys.zip(oldHash.collect{ |k,v| modified(v) })
To get the new hash required. The first version relies on an imperative construct, while the second does not return a Hash, but merely an associative Array, which is not properly equipped to act as a hash (Ruby has no Array#to_hash !).
In Ruby, you can usually do things functionally, just chaining methods and possibly using binary comparisons. However, there (currently) is no way to do the previous in such a manner.

Proposal

Another method, specifically for Hashes, that returns a "re-mapped" Hash. Possibly Hash#collect_to_hash or Hash#remap (which sounds destructive, and might be better as a destructive compliment).

Analysis

This would have no impact on anyone who doesn't need such a method, save for people who delegate to Hashes, and don't expect such a method. It would pull quite a bit of redundance from those who do, however.

Implementation

It would look, in Ruby code, pretty much like my first example.
class Hash # or module Mappable
  def collect_into_hash( &aProc )
    new = Hash.new
    keys.each{ new[key] = aProc.call( key, self[key] ) }
    new
  end
end


Back to RCRchive.


RCR Submission page and RCRchive powered by Ruby, Apache, RuWiki (modified), and RubLog