From: Brian Candler Date: 2003-07-22T01:57:40+09:00 Subject: Re: Proposal: Array#to_h, to simplify hash generation On Tue, Jul 22, 2003 at 01:43:46AM +0900, Brian Candler wrote: > The bit I don't like is Hash#<< taking an array of two elements, rather than > having two arguments I forgot about using Method#arity. New version attached... Brian. class Array # ditto for Enumerable def collect(dest=Array,*args) res = dest.new(*args) if res.method(:<<).arity == 1 each do |item| res << yield(item) end else each do |item| res.send(:<<, *yield(item)) end end res end end class Hash def <<(key,val) self[key] = val end end a = [["one","two"],["three","four"],["five","six"]] p a.collect {|e| e[0]} p a.collect(String,"") {|e| e[1]} p a.collect(Hash) {|e| e} p a.collect(Hash) {|k,v| [v,k]} # like Hash#invert def f(i) i*i; end p [1, 2, 3].collect(Hash) { |i| [i, f(i)] } p [1, 2, 3].collect(String,"") { |i| i.class.to_s } p [1, 2, 3].collect(Array) { |i| Regexp.new(i.to_s) }