I have a ruby script array when each element needs processing :
threads = [] elemets.each do |element| threads.push(Thread.new{process(element)}} end threads.each { |aThread| aThread.join }
how ever due to resource limitations, the script works in an optimal way if no more the four elements are processed at a time.
no I know I can dump the each loop and use a variable to count 4 elements and then wait but is there a cooler ruby way to do it ?
The at() method of an array in Ruby is used to access elements of an array. It accepts an integer value and returns the element. This element is the one in which the index position is the value passed in.
How does each work in Ruby? each is just another method on an object. That means that if you want to iterate over an array with each , you're calling the each method on that array object.
This can be done in a few ways in Ruby. The first is the plus operator. This will append one array to the end of another, creating a third array with the elements of both. Alternatively, use the concat method (the + operator and concat method are functionally equivalent).
An array is a data structure that represents a list of values, called elements. Arrays let you store multiple values in a single variable. In Ruby, arrays can contain any data type, including numbers, strings, and other Ruby objects. This can condense and organize your code, making it more readable and maintainable.
You can enumerate in groups of 4 for an array:
>> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].each_slice(4) {|a| p a} [1, 2, 3, 4] [5, 6, 7, 8] [9, 10, 11, 12]
So you can try something like
elements.each_slice(4) do | batch | batch.each do | element | threads.push(Thread.new{process(element)}} end (do stuff to check to see if the threads are done, otherwise wait ) end
Its may not be what you need, though - I have been up since 3 AM and I only had a couple of hours sleep. :/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With