Split a Ruby Enumerable into chunks
Tuesday, August 7, 2012 at 07:28AM
John Carney in Software Development, ruby

Now and again I've had a need to split an array of strings into chunks divided by certain boundary patterns. Kind of like String.split, but for an array, and with multiple boundary patterns. The problem is something akin to splitting the different sections of a MIME multipart message.

In the latest instance, I wrestled with Ruby's take_while and drop_while for a bit, before giving in and kludging together an ugly state machine solution, which I shipped. However, I wasn't happy with it, so I went back and built a better solution.

The Enumerable.split method below will take an arbitrary number of patterns and split the enumerable object into chunks at each of the pattern boundaries.

An example is given below:

I'm not entirely happy with the name split, but it was the best I could come up with at the time.

Article originally appeared on the inner curmudgeon (http://innercurmudgeon.com/).
See website for complete article licensing information.