如何将Ruby数组拆分为一定数量的较小数组?

时间:2013-12-02 23:54:51

标签: ruby arrays

我有一个大的Ruby数组,我会分成更小的数组。我并不关心每个数组中有多少项,而是关心指定最终会有多少个数组。我将在列中显示项目。例如,如何将数组拆分为两个或三个较小的数组?

3 个答案:

答案 0 :(得分:3)

如果你正在使用Rails(你没说),你可以使用in_groups

%w(1 2 3 4 5 6 7 8 9 10).in_groups(3) {|group| p group}
["1", "2", "3", "4"]
["5", "6", "7", nil]
["8", "9", "10", nil]

http://api.rubyonrails.org/classes/Array.html#method-i-in_groups

或者,如果不是Rails,只需获取该方法的来源......

答案 1 :(得分:2)

如果没有Rails,我会使用each_slice

2.0.0p247 :006 > arr = %w(1 2 3 4 5 6 7 8 9 10)
 => ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] 

2.0.0p247 :007 > n = 3  # how many arrays you want
 => 3

2.0.0p247 :009 > arr.each_slice((arr.size/n.to_f).ceil) {|slice| p slice };nil
["1", "2", "3", "4"]
["5", "6", "7", "8"]
["9", "10"]
 => nil 

答案 2 :(得分:1)

list = (1..10).to_a
nsublists = 3
sublists = []
list.each_slice((list.size.to_f/nsublists).ceil) { |slice| sublists << slice }

sublists # => [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]