2

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?

3 Answers 3

8

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]}
Sign up to request clarification or add additional context in comments.

Comments

5

You could transpose the original array, remove the last block and transpose it again:

arr.transpose[0..2].transpose

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.