From: Shannon Fang Date: 2005-10-25T14:05:07+09:00 Subject: Re: RCR: Array#to_h I am just reading the PickAxe 2e recently... According to Dave, to_h means a representation of the object in hash, however to_hash means this object is inherently compatible with hash, like to_i and to_int... We do need a good name for it :D Shannon >From: "Trans" >Reply-To: ruby-talk@ruby-lang.org >To: ruby-talk@ruby-lang.org (ruby-talk ML) >Subject: Re: RCR: Array#to_h >Date: Tue, 25 Oct 2005 13:57:02 +0900 > >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. > >