Hi --

On Fri, 17 Jan 2003, Tom Payne wrote:

> I use the following snippet a lot, and think it's worth including in
> the Ruby built-in Array class.
>
> class Array
>
>   def to_h(default = nil)
>     result = Hash.new(default)
>     each_with_index do |value, index|
>       result[index] = value
>     end
>     result
>   end
>
> end
>
> Example usage:
>
> [:a, :b, :c].to_h # => {0=>:a, 1=>:b, 2=>:c}

My inclination would be for a basic #to_h to operate more like:

  %w{a b c d} => {"a"=>"b", "c"=>"d"}

and for the method that added in the array indices to be called
something else.  Also, I think you're doing it backwards :-)  For one
thing, if you've got duplicate values in your array, your hash will
end up truncated.  Also, I think an indexed #to_h sort of grows out of
the idea that an array is, or can be viewed as, a hash whose keys
happen to be positive integers.  That means that you'd want the
indices to be the *keys* of the new hash, not the values.

There's a bunch of versions of this floating around....  See the
thread starting at <http://www.ruby-talk.org/6582>, also an RCR at
<http://www.rubygarden.com/article.php?sid=61> (which was posted by
me, though my name isn't on it; I take full responsibility for the
idea of the name "hashify", though I can't really remember why I
proposed that name).


David

-- 
David Alan Black
home: dblack / candle.superlink.net
work: blackdav / shu.edu
Web:  http://pirate.shu.edu/~blackdav