取樣陣列,切片陣列陣列
# sub-arrays are all of the same length
arr = [[1,2,3,4], [5,6,7,8], [2,4,6,8], [1,3,5,7]]
現在,
arr.some_slicing_technique(0..2)
應該給我,
[[1,2,3], [5,6,7], [2,4,6], [1,3,5]]
是否some_slicing_technique
存在嗎?解決這個問題的最好方法是什麼?
取樣陣列,切片陣列陣列
# sub-arrays are all of the same length
arr = [[1,2,3,4], [5,6,7,8], [2,4,6,8], [1,3,5,7]]
現在,
arr.some_slicing_technique(0..2)
應該給我,
[[1,2,3], [5,6,7], [2,4,6], [1,3,5]]
是否some_slicing_technique
存在嗎?解決這個問題的最好方法是什麼?
你可以這樣說:
[[1,2,3,4], [5,6,7,8], [2,4,6,8], [1,3,5,7]].map {|e| e.take(3)}
=> [[1, 2, 3], [5, 6, 7], [2, 4, 6], [1, 3, 5]]
或者,如果你想使用範圍:
[[1,2,3,4], [5,6,7,8], [2,4,6,8], [1,3,5,7]].map {|e| e[0..2]}
你可以調換原始數組,取出最後一塊再次調換它:
arr.transpose[0..2].transpose
一點更通用:
arr = [[1,2,3,4], [5,6,7,8], [2,4,6,8], [1,3,5,7]]
slice_lambda = lambda { |r| lambda{ |x| x[r]} }
arr.map(&slice_lambda[0..2])
# => [[1, 2, 3], [5, 6, 7], [2, 4, 6], [1, 3, 5]]
arr.map(&slice_lambda[1..2])
# => [[2, 3], [6, 7], [4, 6], [3, 5]]