Split a Ruby array into two halves.

To split a Ruby array into two equally-sized (+/-1) parts:

left,right = a.each_slice( (a.size/2.0).round ).to_a

For example:

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

 

This page was generated at 4:16 PM on 26 Feb 2018.
Copyright © 1999 - 2018 Rodney Waldhoff.