Options for processing X elements of an array at a time using Ruby

后端 未结 2 1016
清酒与你
清酒与你 2021-01-22 14:22

We want to process 1000 elements of an array at a time. What are the options for doing this in Ruby?

Obviously, one approach is to do a simple loop and slice 1000 elemen

相关标签:
2条回答
  • 2021-01-22 14:57

    We wound up using each_slice:

    array = [1,2,3,4,5,6,7,8,9,10]
    array.each_slice(3) do |group| 
      puts group
    end
    
    0 讨论(0)
  • 2021-01-22 14:58

    In Rails you can use in_groups_of:

    array = [1,2,3,4,5,6,7,8,9,10]
    array.in_groups_of(3, false).each do |group| 
      puts group
    end
    
    # => [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
    
    0 讨论(0)
提交回复
热议问题