2017-03-10 37 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 
相关问题