RCR: Array#to_h

Maybe what we're actually after here is the equivalent to map/collect
that produces a hash instead. I really don't like the name "hash_map",
but it was either that or "hashify". If you want the index behaviour,
you can do that with an Enumerable.

module Enumerable
  def hash_map
    h = {}
    each do |x|
      k,*v = yield(*x)
      h[k] = *v
    end
    h
  end
end
class Hash
  def hash_map!(&block)
    replace(hash_map(&block))
  end
end

#now we can create a hash with all the values double that of a previous
hash:

hash = {'a'=>1, 'b'=> 2}
hash2 = hash.hash_map { |k,v| [k,(v*2)]}

#=> {"a"=>2, "b"=>4}

#or form a hash from an array:

arr = [1,2,3,4,5,6]
hash3 = arr.hash_map { |x| [x, x * 5] }

#=>{5=>25, 6=>30, 1=>5, 2=>10, 3=>15, 4=>20}

The main problem with the above is the fact that the block needs to
return two values, and it's quite awkward to do that.

···

-----Original Message-----
From: nobuyoshi nakada [mailto:nobuyoshi.nakada@ge.com]
Sent: Tuesday, 25 October 2005 3:39 PM
To: ruby-talk ML
Subject: Re: RCR: Array#to_h

Hi,

At Tue, 25 Oct 2005 13:37:01 +0900,
Trans wrote in [ruby-talk:162411]:
> I think the proposal is over specialized. Why should the array
> elements neccessarily become keys?

Yes, agreed, and I doubt that there is a solution which
satisfy everyone for this issue.

--
Nobu Nakada

#####################################################################################
This email has been scanned by MailMarshal, an email content filter.
#####################################################################################