2014-10-29 65 views
0

我试图将一个名称数组推到二维数组中。当二维数组遇到4个条目时,添加到数组的下一个位置。例如:推到二维数组

groups[0] 
[ 
    [0] "bobby", 
    [1] "tommy", 
    [2] "johnny", 
    [3] "brian" 
] 

groups[1] 
    [0] "christina", 
    [1] "alex", 
    [2] "larry", 
    [3] "john" 
] 

下面是我试图做到这一点,它不工作。我知道有可能是一些内置的功能,红宝石,将自动完成这个过程,但我想它首先手动写出来:提前

def make_group(the_cohort) 
    y=0 
    x=1 
    groups=[] 

    the_cohort.each do |student| 
     groups[y].push student 
     x+=1 
     y+=1 && x=1 if x==4 
    end 
end 

感谢。使用Ruby 2.1.1p73

+0

这不是一个二维数组,Ruby没有那些(除非你'Matrix')。这只是一个数组的数组。 – 2014-10-29 01:59:38

+0

Enumerable#each_slice,由@ChrisHeald提到,是专门为此任务制作的,但还有其他方法可以完成此任务。这里有一个:'(0 ... arr.size).step(4).map {| i | arr [i,4]}'。 – 2014-10-29 03:24:45

回答

3

你的算法可以表示为:

1. If the last array in groups has 4 entries, add another array to groups 
2. Push the entry into the last array in groups 

在代码:

groups = [[]] 
the_cohort.each do |student| 
    groups.push [] if groups.last.length == 4 
    groups.last.push student 
end 

对于每一个学生,它会看看groups的最后一个条目(这是唯一可能不完整的),决定是否需要添加一个新的子数组到groups,然后将学生推入最后一个子数组。

也就是说,这听起来像你真正想要的是取一个名称列表,并将它们分成四组。 Ruby有这个建在已经通过each_slice

the_cohort = %w(bobby tommy johnny brian christina alex larry john) 
the_cohort.each_slice(4).to_a 
# => [["bobby", "tommy", "johnny", "brian"], ["christina", "alex", "larry", "john"]] 
+0

谢谢你,groups = [[]]正是我需要做的,因为list列表为null,你不能推送它。 我知道each_slice,但想在使用内置函数之前“手动”解决问题。感谢您花时间解释两者! – theartofbeing 2014-10-29 16:26:55