Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split (chunk) a Ruby array into parts of X elements? [duplicate]

Tags:

arrays

ruby

People also ask

How do you split an array in Ruby?

split is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified. Here the pattern can be a Regular Expression or a string. If pattern is a Regular Expression or a string, str is divided where the pattern matches.

How do you divide an array into equal Subarrays?

A Simple solution is to run two loop to split array and check it is possible to split array into two parts such that sum of first_part equal to sum of second_part. Below is the implementation of above idea.

How do you split an item in an array?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


Take a look at Enumerable#each_slice:

foo.each_slice(3).to_a
#=> [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["10"]]

If you're using rails you can also use in_groups_of:

foo.in_groups_of(3)