On Jan 26, 4:52 am, Thomas Hafner <tho... / hafner.NL.EU.ORG> wrote:
> Hello,
>
> did I miss some standard library function? Anyway, then I'll do it on
> my own:
>
> def cartprod(*args)
>   result = [[]]
>   while [] != args
>     t, result = result, []
>     b, *args = args
>     t.each do |a|
>       b.each do |n|
>         result << a + [n]
>       end
>     end
>   end
>   result
> end
>
> Example:
> cartprod([1,2],[3,4,5],[6,7,8])
> => [[1, 3, 6], [1, 3, 7], [1, 3, 8], [1, 4, 6], [1, 4, 7], [1, 4, 8],
>     [1, 5, 6], [1, 5, 7], [1, 5, 8], [2, 3, 6], [2, 3, 7], [2, 3, 8],
>     [2, 4, 6], [2, 4, 7], [2, 4, 8], [2, 5, 6], [2, 5, 7], [2, 5, 8]]
>
> Regards
>   Thomas

Here's a shorter but slower way.

def cart_prod( *args )
  args.inject([[]]){|old,lst|
    lst.inject([]){|new,e|
      new + old.map{|c| c.dup << e}}}
end

Its results are ordered differently.