2016-04-21 49 views
4

愚蠢的問題,我想,但我已經搜索了高和低的一個明確的答案,並沒有發現任何東西。每個索引達到一定數量的紅寶石在軌道上

array.each_with_index |row, index| 
    puts index 
end 

現在,假設我只想打印數組的前10項。

array.each_with_index |row, index| 
    if (index>9) 
    break; 
    end 
    puts index 
end 

有沒有比這更好的方法?

回答

12

使用Enumerable#take

array.take(10).each_with_index |row, index| 
    puts index 
end 

如果條件比較複雜,使用take_while

經驗法則是:迭代器可能被鏈接:

array.take(10) 
    .each 
    # .with_object might be chained here or there too! 
    .with_index |row, index| 
    puts index 
end 
3

另一種解決方案是使用Enumerable#first

array.first(10).each_with_index do |row, index| 
    puts index 
end