Combine array of array into all possible combinations, forward only, in Ruby

后端 未结 3 1185
既然无缘
既然无缘 2020-12-08 14:23

I have an array of arrays, like so:

[[\'1\',\'2\'],[\'a\',\'b\'],[\'x\',\'y\']]

I need to combine those arrays into a string containing all

3条回答
  •  臣服心动
    2020-12-08 15:09

    Pure, reduce with product:

    a = [['1','2'],['a','b'],['x','y']]
    a.reduce() { |acc, n| acc.product(n).map(&:flatten) }.map(&:join)
    #  => ["1ax", "1ay", "1bx", "1by", "2ax", "2ay", "2bx", "2by"]
    

提交回复
热议问题