clonecq clonecq - 1 month ago 5
Ruby Question

Other ways of converting part of array to subarray in Ruby?

When parsing CSV file I need to combine fields of a row into an array starting from 4th field (3rd array element). I want to manipulate each row as in example below:
Original array:

array1 = [1,2,3,4,5]


Changed array:

array2 = [1,2,3,[4,5]]


My code is here:

array1[0..2].push(array1[3..array1.length])

=> [1, 2, 3, [4, 5]]


My question is: Is there a better/cleaner/simpler way to convert part of an array into subarray?

Answer

There is! You can do this a = a[0..2] + [a[3..-1]]. In ruby + can be used to concatenate arrays. Additionally, n..-1 gives you elements n to the end of the array. As a caveat, + is slower and more expensive than concat so if you were to do a[0..2].concat([a[3..-1]) it will be cheaper and faster.

Comments