From: Trans Date: 2005-10-25T13:57:02+09:00 Subject: Re: RCR: Array#to_h Actually this has been bugging me as I currently have these: module Enumerable # Produces a hash from an Enumerable with index for keys. # # a1 = [ :a, :b ] # a1.to_h #=> { 0=>:a, 1=>:b } # def to_h( &blk ) h = {} if block_given? each_with_index{ |e,i| h[i] = blk.call(e,i) } else each_with_index{ |e,i| h[i] = e } end h end end class Array # Produces a hash for an Array, or two arrays. # It is just like Enumerbale#to_h but with an # extra feature: If an array is given as the # values, it is zipped with the receiver, # to produce the hash. # # a1 = [ :a, :b ] # a2 = [ 1, 2 ] # a1.to_h(a2) #=> { :a=>1, :b=>2 } # def to_h(values=nil) h = {} if values size.times{ |i| h[at(i)] = values.at(i) } else each_with_index{ |e,i| h[i] = e } end h end # Converts an associative array into a hash. # # a = [ [:a,1], [:b,2] ] # a.assoc_to_h #=> { :a=>1, :b=>2 } # # a = [ [:a,1,2], [:b,3,4] ] # a.assoc_to_h(true) #=> { :a=>[1,2], :b=>[3,4] } # def assoc_to_h(arrayed=nil) h = {} if arrayed each{ |e| h[e.first] = e.slice(1..-1) } else each{ |e| h[e.first] = e.last } end h end end I wish there was a good way just to have a single Array#to_h, but it doesn;t seem reasonable. Perhaps Enumerable#to_h could be #to_hash? T.