From: "David A. Black" Date: 2009-02-12T10:28:17+09:00 Subject: Re: Array#to_hash Hi -- On Thu, 12 Feb 2009, William James wrote: > Trans wrote: > >> Would any problems arise from extending Array with this? >> >> # Convert an array into an indexed hash. >> # >> # [:a,:b,:c].to_hash #=> {0=>:a,1=>:b,2=>:c} >> # >> def to_hash >> h = {} >> each_with_index do |v, i| >> h[i] = v >> end >> h >> end >> >> Thanks, >> T. > > Always remember: > > "We don't need no stinkin' loops!" > > a=[:a,:b,:c] > ==>[:a, :b, :c] > Hash[ *(0...a.size).zip(a).flatten ] > ==>{0=>:a, 1=>:b, 2=>:c} You'd want to use flatten(1) so as to avoid over-flattening. (Available as the flatten_x extension for 1.8.6.) David -- David A. Black / Ruby Power and Light, LLC Ruby/Rails consulting & training: http://www.rubypal.com Coming in 2009: The Well-Grounded Rubyist (http://manning.com/black2) http://www.wishsight.com => Independent, social wishlist management!