"Marcel Molina Jr." <marcel / vernix.org> writes:

> On Tue, Oct 25, 2005 at 12:10:18PM +0900, Shannon Fang wrote:
>> Abstract
>> 
>> A simple method that construct a hash from an array. Just like Hash#to_a 
>> return an array from hash.
>
> Having your proposed to_h accept a block is a nice idea but as it is you can
> do the non-block version quite easily:
>
>>> Hash[*%w(a b c d)]
> => {"a"=>"b", "c"=>"d"}
>>> keys = %w(a b c d)
> => ["a", "b", "c", "d"]
>>> values = [1, 2, 3, 4]
> => [1, 2, 3, 4]
>>> Hash[*keys.zip(values).flatten]
> => {"a"=>1, "b"=>2, "c"=>3, "d"=>4}

And the block version:

>> a = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
>> Hash[*a.map {|e| [e, 2*e]}.flatten]
=> {5=>10, 1=>2, 2=>4, 3=>6, 4=>8}

Steve