From: Robert Klemme Date: 2006-03-28T19:23:55+09:00 Subject: Re: Noob: The ruby way to multiple Array by multiple? Eric Luo wrote: > I want to make a Array multipled by another Array, and the following semantic. > For example: > [1, 2, 3] * [4, 5] > then I will want [[1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [3, 5]] returned. > > I have the following code snippet to implement this function: > > class Array > alias_method :orig_multiple, :* > def *(arg) > case arg > when Array > if arg.empty? > self > else > inject([]) do |product, item| > product.concat(arg.collect do |i| > case item > when Array > item.clone << i > else > [item, i] > end > end) > end > end > else > orig_multiple(arg) > end > end > end > > It works but seems ugly. > > Could anyone please to give me a clue to make it beauty and rubish! > > Thx in advance. > Eric res = [] a1.each {|e1| a2.each {|e2| res << [e1,e2]}} Or, if you prefer inject a1.inject([]) {|arr,e1| a2.each {|e2| arr << [e1,e2]}; arr } Kind regards robert