To split an array in Ruby, you can use the slice
method to create new arrays representing the split parts.
In this example,
numbers
with integer elements.slice
method to extract parts of numbers
into new arrays.numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
slice1 = numbers.slice(0, 3)
slice2 = numbers.slice(3, 3)
slice3 = numbers.slice(6, 3)
puts slice1.join(', ') + ' | ' + slice2.join(', ') + ' | ' + slice3.join(', ')
1, 2, 3 | 4, 5, 6 | 7, 8, 9
In this tutorial, we learned How to Split an Array in Ruby language with well detailed examples.