From: Shannon Fang Date: 2005-10-25T12:10:18+09:00 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