Jay Fields: Array#chunk
Jay Fields of ThoughtWorks posted an interesting problem: break an Array up into a given number of “chunks”. He provides an example implementation and unit tests that define the expected behavior.
I posted my solution in a comment, but here it is again (I really need to figure out how to get syntax coloring…):
class Array def chunk(number_of_chunks) chunks = (1..number_of_chunks).collect { [] } self.each_with_index do |item, index| chunks[index % number_of_chunks] << item end chunks end
alias / chunkend
My solution is a little different than his. First, mine doesn’t modify the contents of the Array; his does. Since his does, the method should really be named “chunk!”, that exclamation point being the convention that indicates that it mutates the instance on which it is called. The unit tests don’t enforce one or the other, so I decided to follow convention.
Second, I’ve got one loop, which is over the Array being chunked. He’s got a nested loop, which I think increases the complexity quite a bit.
There’s a little bit of cleverness in my solution. I figure out which chunk to add the item to using the % modulus operator. This may not be a very common idiom, but it works and you don’t need a separate counter with boundary testing to cycle back to zero.
Jeremy, I like your solution. I think it’s a bit ‘trickier’ than mine. Not that I have a problem with that, in fact I think it’s cool. But, from a maintenance perspective that would be a concern.
Thanks for the solution.
Thanks, Jay. Like I mentioned, this was an interesting exercise that took some thought.
I do think it’s “trickier”, which is what I meant by “clever”. (Raji, this is for you.) Clever code is usually bad, unless it’s a common kind of clever, or it’s well commented. I personally wouldn’t have a problem using % to derive the index, but I can see how it could be confusing.