Reputation: 1876
Sample 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]]
Now,
arr.some_slicing_technique(0..2)
should give me,
[[1,2,3], [5,6,7], [2,4,6], [1,3,5]]
Does some_slicing_technique
exist? What would be the best way to solve this?
Upvotes: 2
Views: 139
Reputation: 9225
A little more generic:
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]]
Upvotes: 1
Reputation: 2703
You can do it like this:
[[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]]
Or if you want to use ranges:
[[1,2,3,4], [5,6,7,8], [2,4,6,8], [1,3,5,7]].map {|e| e[0..2]}
Upvotes: 8
Reputation: 601
You could transpose the original array, remove the last block and transpose it again:
arr.transpose[0..2].transpose
Upvotes: 5