OneBite.Dev - Coding blog in a bite size

split an array into smaller arrays in Ruby

Code snippet on how to split an array into smaller arrays in Ruby

array = ["john", "sara", "jill", "bob", "alan", "betty"]
smaller_arrays = array.each_slice(2).to_a

This code first defines an array named ‘array’ containing 6 strings. It then creates a new array named ‘smaller_arrays’ and assigns the result of a call to the ‘each_slice’ method on the ‘array’ array, with an argument of 2, followed by the ‘to_a’ method.

In English, what this code is doing is taking the original array of 6 strings and splitting it into smaller arrays of 2 strings each. It then converts the result into an array and assigns it to ‘smaller_arrays’. The resulting array is an array of 3 arrays with 2 strings in each.

ruby