How to chunk an array in Ruby

前端 未结 2 853
暖寄归人
暖寄归人 2020-11-28 09:16

In Ruby 1.8.6, I have an array of, say, 100,000 user ids, each of which is an int. I want to perform a block of code on these user ids but I want to do it in chunks. For e

相关标签:
2条回答
  • 2020-11-28 09:32

    Rails has in_groups_of, which under the hood uses each_slice.

    userids.in_groups_of(100){|group|
      //process group
    }
    
    0 讨论(0)
  • 2020-11-28 09:52

    Use each_slice:

    require 'enumerator'
    userids.each_slice(100) do |a|
      # do something with a
    end
    
    0 讨论(0)
提交回复
热议问题