From: Jason Creighton Date: 2003-07-22T01:02:53+09:00 Subject: Re: Proposal: Array#to_h, to simplify hash generation On Mon, 21 Jul 2003 05:32:25 GMT Martin DeMello wrote: > To me, 'hashify' implies taking an assoc array and converting it to hash > form (or perhaps the perl-influenced [a, b, c, d] -> {a=>b, c=>d}). I > still can't think of a name for the useful case :) make_hash, perhaps .. > > *(1..10).make_hash {|i| f(i)} > > or maybe the complementary hash_to and hash_from, where the block is > respectively the value and the key for the corresponding array entry :) I'd like the code to be something like this: module Enumerable def to_h h = Hash.new if block_given? self.each { |e| h[e] = yield(e) } else self.each { |key, value| h[key] = value } end return h end end >> (1..5).to_h { |n| n*n } => {5=>25, 1=>1, 2=>4, 3=>9, 4=>16} >> [ [1,2], [3,4] ].to_h => {1=>2, 3=>4} >> [ [1,2], [3,4] ].to_h.to_a => [[1, 2], [3, 4]] >> [ [1,2], [3,4] ].to_h.to_a.to_h => {1=>2, 3=>4} >> Dir["/bin/d*"].to_h { |f| File.size(f) } => {"/bin/dnsdomainname"=>9332, "/bin/date"=>25728, "/bin/dd"=>29492, "/bin/dmesg"=>3924, "/bin/df"=>27368, "/bin/domainname"=>9332} I would almost prefer [1,2,3,4].to_h => {1=>2, 3=>4}, but Hash#to_h returns a nested array, so that's what this code does. Plus it's easier to implement. :-) Jason Creighton