Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 236 Vote(s) - 3.43 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to chunk an array in Ruby

#1
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 example, I want to process them 100 at a time. How can I easily achieve this as simply as possible?

I could do something like the following, but probably there's an easier way:

a = Array.new
userids.each { |userid|
a << userid
if a.length == 100
# Process chunk
a = Array.new
end
}
unless a.empty?
# Process chunk
end

Reply

#2
Use [`each_slice`][1]:

require 'enumerator' # only needed in ruby 1.8.6 and before
userids.each_slice(100) do |a|
# do something with a
end

[1]:

[To see links please register here]

Reply

#3
Rails has [`in_groups_of`][1], which under the hood uses `each_slice`.

userids.in_groups_of(100){|group|
//process group
}


[1]:

[To see links please register here]

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through