Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby working on array elements in groups of four

Tags:

ruby

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 ?

like image 758
Eli Avatar asked Jan 01 '10 10:01

Eli


People also ask

How do you access the elements of an array in Ruby?

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.

What does .each mean in Ruby?

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.

How do you add an array together in Ruby?

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).

How does array work in Ruby?

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.


1 Answers

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. :/

like image 94
Rilindo Avatar answered Oct 06 '22 12:10

Rilindo