Crashalot
Crashalot

Reputation: 34523

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

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 elements from the array until no more elements remain, but was curious if there are other more elegant options.

This is for a Rails app (RoR 3.2.12).

Upvotes: 2

Views: 60

Answers (2)

Crashalot
Crashalot

Reputation: 34523

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

Upvotes: 1

infused
infused

Reputation: 24367

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]]

Upvotes: 2

Related Questions