2

I'm looking for a method to divide a one dimensional array by a number n to create a multidimensional array with each element having (at most) length n. For example

[1,2,3,4,5,6] / 3

should result in:

[[1,2,3],[4,5,6]]

1 Answer 1

5

This should do it...

chunkedArr = arr.each_slice(3).to_a;
Sign up to request clarification or add additional context in comments.

3 Comments

I knew it was something easy. Thanks.
@pguardiario I couldn't get it to work in CodePad.org and I'm not a Ruby guru, is it working for you?
More fun: class Array; def /(n); each_slice(n).to_a; end; end :)

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.