做一个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循环来说是没有问题的。我想知道是否有更简单的解决方案。
3条答案
按热度按时间pgccezyw1#
有:)
olhwl3o22#
g6baxovj3#
请注意,还有
values_at
,它可以接受单个项目,不同位置的项目以及位置范围: