David Alan Black <dblack / candle.superlink.net> writes:

> I was wondering about a block form.  I'm not sure exactly what it
> would do -- specifically, whether the results of the block would
> pertain to the keys or the values of the new hash.  In other words,
> would it be this:
> 
>       each_with_index { |e,i| h[i] = yield(i, e) }
> 
> or this:
> 
>       each_with_index { |e,i| h[yield(i, e)] = e }
>

or
     module Enumerable
       def to_h(value = 1)
         h = {}
         if block_given?
           each_with_index {|e,i| hk,hv = yield(e,i); h[hk] = hv }
         else
           each {|hv| h[hv] = value }
         end
         h
       end
     end

     ary = %w{one two three}

     ary.to_h        #=> {"one"=>1, "three"=>1, "two"=>1}
     ary.to_h false  #=> {"one"=>false, "three"=>false, "two"=>false}

     ary.to_h { |word, index| [index, word]}
                     #=> {0=>"one", 1=>"two", 2=>"three"}

     ary.to_h { |word, index| [word, index]}
                     #=> {"one"=>0, "three"=>2, "two"=>1}

     ary.to_h { |word,| [word.upcase, true]}
                     #=> {"ONE"=>true, "THREE"=>true, "TWO"=>true}

> Another question on the hypothetical to_h subject: would there be any
> reason for to_h not to be part of Enumerable, rather than Array?

Sounds reasonable to me.



Dave