From: Michael Ulm Date: 2005-12-14T00:47:13+09:00 Subject: Re: Array.invert Christer Nilsson wrote: > I would like to see invert "rubyfied". > (Yes, I'm trying to get a grip of what this word means :-) > > class Array > def invert > res=[] > for i in 0...self.size > if self[i] != nil then > for b in self[i] > res[b] = [] if res[b].nil? > res[b] << i > end > end > end > res > end > end > I suggest class Array def invert result = [] each_with_index do |ary, idx| next if ary.nil? ary.each {|val| (result[val] ||= []).push(idx)} end result end end As a matter of taste, you may want to write the two middle lines in just one line as ary.each {|val| (result[val] ||= []).push(idx)} unless ary.nil? HTH, Michael -- Michael Ulm R&D Team ISIS Information Systems Austria tel: +43 2236 27551-219, fax: +43 2236 21081 e-mail: michael.ulm@isis-papyrus.com Visit our Website: www.isis-papyrus.com