2017-03-10 38 views
0

做一個紅寶石問題和思考自己,必須有一個更簡單的方法。我想將一個指定索引的數組拆分爲兩個子數組。第一個子數組包含指定索引號的數字,第二個子數組包含指定索引之後的數字。Ruby,是否有內置方法將數組拆分爲指定索引處的兩個子數組?

([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 

這是while循環沒有問題。我想知道是否有更簡單的解決方案。

回答

2

有:)

arr1 = [2, 1, 2, 2, 2].take 2 
arr2 = [2, 1, 2, 2, 2].drop 2 
1
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 
相關問題