Problem is - which [].to_h is intuitive. There's a to_h in nano:

http://nano.rubyforge.org/doc/classes/Array.html#M000057

You can already do:

a = [1, 2, 3, 4, 5]
hash = a.inject({}) {|h,x| h[x] = x*2}

Or:

class Array
	def to_h
		a.inject({}) { |h,x| h[x] = yield(x) }
	end
end
hash = a.to_h { |x| x*2}

I think the inject method most clearly shows what's going on. 

> -----Original Message-----
> From: Shannon Fang [mailto:xrfang / hotmail.com] 
> Sent: Tuesday, 25 October 2005 1:10 PM
> To: ruby-talk ML
> Subject: RCR: Array#to_h
> 
> Hi there,
> 
> I have registered 2 accounts for RCRkive, but all failed... 
> So I posted here.
> 
> Abstract
> 
> A simple method that construct a hash from an array. Just 
> like Hash#to_a return an array from hash.
> 
> Problem
> 
> Consider this cenario: I programmed a multi-threaded web page 
> downloader. 
> One of its input is an array of urls to download. In the 
> program, I wanted to use a hash like 
> {'http://ruby-lang.org/index.html' => '200'}, i.e., use a 
> hash to record the return code of the http request. This way 
> I can avoid re-download a page, or miss a page.
> 
> For the user of this download program, it is much easier to 
> use an Array instead of a Hash:
> 
> d = WebPageDownloader.new
> d.links = IO.readlines('list.txt')
> 
> Hence, in the program we want to do:
> 
> @links = @links.to_h
> 
> Proposal
> 
> Add a method to_h (not to_hash) in the Array class, so that user can:
> 
> a = [1, 2, 3, 4, 5]
> p a.to_h { |i, v| v * 2}  --> {5=>10, 1=>2, 2=>4, 3=>6, 4=>8}
> p a.to_h(3)                 --> {5=>3, 1=>3, 2=>3, 3=>3, 4=>3}
> 
> 
> Anaysis
> 
> This is very convenient for users who need this feature, and 
> it will not affect behavior of the Array class in anyway for 
> those do not need this feature.
> 
> Please refer to RCR278, which is similar but not same.
> 
> Implementation
> 
> class Array
>   public
>   def to_h(value = nil)
>     _hash = {}
>     self.each_index do |i|
>       v = self[i]
>       if block_given? then
>         _hash[v] = yield(i, v)
>       else
>         _hash[v] = value
>       end
>     end
>     _hash
>   end
> end
> 
> Please comment.
> 
> Thanks,
> Shannon
> 
> 
> 
> 
> 
#####################################################################################
This email has been scanned by MailMarshal, an email content filter.
#####################################################################################