Ruby,是否有一个内置的方法将数组拆分为两个指定索引的子数组?

s1ag04yj  于 12个月前  发布在  Ruby
关注(0)|答案(3)|浏览(80)

做一个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循环来说是没有问题的。我想知道是否有更简单的解决方案。

pgccezyw

pgccezyw1#

有:)

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

olhwl3o22#

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
g6baxovj

g6baxovj3#

请注意,还有values_at,它可以接受单个项目,不同位置的项目以及位置范围:

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]

相关问题