From: walter a kehowski Date: 2005-08-10T02:31:09+09:00 Subject: Re: cartesian product > > You can do it a bit shorter. Note that you don't need the "a=[]" and the > "self.": > The two versions both work. Which is better? class Array def cartprod(b=[]) # def cartprod(*b) if b.empty? then #assume self an array of arrays inject {|cp,x| cp.cartprod(x) } else inject([]) {|a,x| b.inject(a) {|a,y| a << [x,y]}} # inject([]) {|a,x| b[0].inject(a) {|a,y| a << [x,y]}} end end end #Array a=[1,2,3] b=[4,5,6] p a.cartprod(b) p [a,b].cartprod