Reputation: 1437
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.
Upvotes: 6
Views: 3677
Reputation: 1
For cases where one of the subarrays has length 1, you can use the splat operator.
a = [1, 2, 3]
*b, c = a
b
# => [1, 2]
c
# => [3]
b, *c = a
b
# => [1]
c
# => [2, 3]
Upvotes: 0
Reputation: 5617
There is :)
arr1 = [2, 1, 2, 2, 2].take 2 #=> [2, 1]
arr2 = [2, 1, 2, 2, 2].drop 2 #=> [2, 2, 2]
Upvotes: 6
Reputation: 556
Note that there is also values_at
which can take single items, items at different positions, and ranges of positions:
a = [0,1,2,3,4,5,6,7,8,9]
a.values_at(1,3)
# => [1, 3]
a.values_at(3..7)
# => [3, 4, 5, 6, 7]
Upvotes: 0
Reputation: 146053
def split a, i
[a[0...i], a[i..-1]]
end
p split [2,1,2,2,2], 2
# here is another way
class Array
def split i
[self[0...i], self[i..-1]]
end
end
p [2,1,2,2,2].split 2
Upvotes: 2