DAY 12
0
Modern Web

## How to mix around Unlimited Array

(不能隨意胡言亂語了)

``````A = [[a,b,c],[1,2]]
A.do_something
=> [[a,1],[a,2],[b,1],[b,2],[c,1],[c,2]]
``````

``````A = [[a,b,c],[1,2],[x,y]]
A.do_something
=> [[a,1,x],[a,2,x],[b,1,x],[b,2,x],[c,1,x],[c,2,x],[a,1,y],[a,2,y],[b,1,y],[b,2,y],[c,1,y],[c,2,y]]
``````

### 如果你有自己試著解開，也可以晚一點再往下看我的解法

``````def speks_array_magic(array)
# arr = [["1","2"],["3","4"]..]
temp_result
final_result = []
# 特例：只有一種規格，如[["1","2"...]]
if arr.length == 1
final_result = arr.flatten
else
arr.each do |v|
if arr[0] == v
temp_result = v
else
temp_result = temp_result.product(v)
end
end
temp_result.each do |v|
final_result << v.flatten
end
end
final_result
end
``````

### flatten

``````[[0,1,2],[1,2,3]].flatten
=> [0, 1, 2, 1, 2, 3]
``````

### product

``````[1,2,3].product([4,5])     #=> [[1,4],[1,5],[2,4],[2,5],[3,4],[3,5]]
[1,2].product([1,2])       #=> [[1,1],[1,2],[2,1],[2,2]]
[1,2].product([3,4],[5,6]) #=> [[1,3,5],[1,3,6],[1,4,5],[1,4,6],
#     [2,3,5],[2,3,6],[2,4,5],[2,4,6]]
[1,2].product()            #=> [[1],[2]]
[1,2].product([])          #=> []
``````

Ruby礦工的Rails地圖30