2011-05-23 44 views
2

我正在使用ruby 1.8.5,而數組的each_slice()方法不起作用。在Ruby 1.8.5中是否存在Array#each_slice()的等價物?

我的代碼是這樣的:

array.each_slice(3) do |name,age,sex| ..... end 

有沒有實現我的舊版本紅寶石相同的功能的任何其他方式。

+0

@the鐵皮人:什麼是錯的紅寶石1.8標籤? – 2011-05-24 00:08:04

回答

5

烘烤自己:

module Enumerable 
    def each_slice(n) 
    res = [] 
    self.each do |el| 
     res << el 
     if res.size == n then 
     yield res.dup 
     res.clear 
     end 
    end 
    yield res.dup unless res.empty? 
    end 
end 
+0

真棒..這真的很棒..非常感謝你.. – sundar 2011-05-23 10:43:46

0

我沒有得到1.8.5,但是你可以試試這個

0.step(array.size, 3) do |i| 
    name, age, sex = array[i], array[i+1], array[i+2] 
    ... 
end 
+0

非常感謝你的回覆。在上面的代碼中,比如說如果沒有。的元素是3,它工作正常的一次迭代,但在第二次和第三次迭代,名稱,年齡,性別返回零... – sundar 2011-05-23 10:26:02

+0

@floor:嘿這工程0.step(array.size/3,3)做|我| .. end非常感謝你.. – sundar 2011-05-23 10:33:14

相關問題