[英]Is there a Ruby 1.8.7 built-in to split an array into same sized subarrays?
我已經開始了:
def split_array(array,size)
index = 0
results = []
if size > 0
while index <= array.size
res = array[index,size]
results << res if res.size != 0
index += size
end
end
return results
end
如果我在[1,2,3,4,5,6]
上運行它,如split_array([1,2,3,4,5,6],3)
,它將產生這個數組:
[[1,2,3],[4,5,6]]
。 在Ruby 1.8.7中是否有可以做到這一點的東西?
[1,2,3,4,5,6].each_slice(3).to_a
#=> [[1, 2, 3], [4, 5, 6]]
對於1.8.6:
require 'enumerator'
[1,2,3,4,5,6].enum_for(:each_slice, 3).to_a
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.