Fun With Ruby Arrays

I’ve been working on a personal project for the last week, and it involves a lot of work with creating, sorting, and managing arrays. As a result of this work, I’ve discovered a few fun and very helpful (duh) methods that I’ve put to good use.

  1. each_cons(2)each_cons takes an input array, and returns an enumerator of new arrays of x length, made by grouping every x elements in the original array. Rather than relying on each_with_index to manually build the groups, this does it all in one go. Interestingly enough, grouping array elements like this was the basis for a programming challenge I failed (hard) during an interview recently. Whoops. Now I know.
  2. chunkchunk groups elements based on the return of the block you pass to it. In my case, I’m using it to find continuous dates, and count the number of said continuous period. Makes for a very pretty one-liner.
  3. each_sliceeach_slice is kind of line each_cons, without the overlap. E.g. - [1,2,3,4].each_slice(2) would make [[1,2],[3,4]], whereas [1,2,3,4].each_cons(2) would make [[1,2],[2,3],[3,4]].

More to follow soon!