I work for the Department of Redundancy Department and I’m thinking
there must be a better, more elegant way to doing the following:
With an array of 200 elements
Call a method to act on 10 elements at a time
Repeat until all elements are processed.
Return the processed array.
Here’s my solution to the above:
BEGIN
class Array
def process(method_obj, batch_size = 10, fin = [])
if (this_batch = self.first(batch_size)).size > 0
fin.concat method_obj.call(this_batch)
(self - this_batch).process(method_obj, batch_size, fin)
else
return fin
end
end
end
def munge(ary)
ary.collect { |e| e.+ 10 }
end
my_meth = method(:munge)
ARY = [1,2,3,4,5,6]
p ARY.process(my_meth, 2) # run my_meth against 2 elements at a time
END
The above produces: [11, 12, 13, 14, 15, 16]
This is just a trivial example, but, for what I’m actually doing
there’s a limit of 100 items that can be processed by this mysterious
(dynamic) method, hence the need to “batch” process the array.
Does my solution scream newb? Anyone have a suggestion that would
“own me with easy”?
Thanks in advance for any comments.
Ben