Split a Ruby array into N equally-sized parts.

To split a Ruby array into n equally-sized parts:

a.each_slice( (a.size/n.to_f).round ).to_a

For example:

a = [1,2,3,4,5]; n = 3                     # => 3
a.each_slice( (a.size/n.to_f).round ).to_a # => [[1, 2], [3, 4], [5]]
Tagged ruby and dev.

 

This page was generated at 9:56 PM on 15 Jan 2016.
Copyright © 1999 - 2016 Rodney Waldhoff.