2014-10-29 66 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