Splitting an array in half in Ruby

So I have a collection of objects I need to split into two approximately equal arrays. Luckily, there is the partition method in Ruby:

i = 0
count = User.count
group_one, group_two = User.all.partition { i += 1; i < count / 2 }

The partition method iterates over each object, with the object being pushed to the first array if the block evaluates to true, and vice-versa.

Alternatively, we could use in_groups_of if we’re using Rails:

group_one, group_two = User.all.in_groups_of(User.count / 2)

Subscribe to Codebeef

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe