切片数组

时间:2012-01-31 22:31:18

标签: ruby arrays multidimensional-array

示例数组,

# 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是否存在?解决这个问题的最佳方法是什么?

3 个答案:

答案 0 :(得分:8)

你可以这样做:

[[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]}

答案 1 :(得分:5)

您可以转置原始数组,删除最后一个块并再次转置它:

arr.transpose[0..2].transpose

答案 2 :(得分:1)

更通用一点:

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]]