0

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?

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Actually, I just realized I need the resulting array to be like this; ["1", "2", "3", [4, 5]] - convert String to Integer for subarray. Utilizing your suggestion my code looks like this:
a = ["1","2","3","4","5"] a = a[0..2].concat([a[3..-1].map(&:to_i)]) can this be improved? Sorry, I do's seem to be able to edit this comment
What does "cheaper" in "cheaper and faster" mean? You could also write a[0..2] << a[3..-1].
@Cary Awesome profile read, by the way ;) would you comment on my comment? is there a better way to convert subarray to Integers? a = ["1","2","3","4","5"] a = a[0..2].concat([a[3..-1].map(&:to_i)]) there seem to always be another way in Ruby.
@CarySwoveland "cheaper" means less memory intense. a + b creates a new array so three arrays have memory allocated whereas a.concat(b) concatenates b to a so only two arrays have memory allocated. Faster means that it runs more quickly.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.