Search code examples
ruby

Ruby, is there a built in method to split an array into two sub arrays at a specified index?


Doing a ruby problem and thinking to myself, there must be an easier way.

I want to split an array at a specified index into two sub arrays. The first sub array containing the numbers up to the specified index, and the second sub array containing the numbers after and including the specified index.

Example

([2, 1, 2, 2, 2],2) => [2,1] [2,2,2]
#here, the specified index is two, so the first array is index 0 and 1, 
the second is index 2, 3, and 4. 

def array_split(arr,i)
  arr1 = []
  arr2 = []
  x = 0

  while x < arr.count 
    x < i ? arr1 << arr[x] : arr2 << arr[x]
    x += 1
 end 

 return arr1, arr2
end

This was no issue with a while loop. I want to know if there is a simpler solution.


Solution

  • There is :)

    arr1 = [2, 1, 2, 2, 2].take 2 #=> [2, 1]
    arr2 = [2, 1, 2, 2, 2].drop 2 #=> [2, 2, 2]