The problem that can occur with each_cons is that it iterates through pairs of n-1 (if the length of the Enumerable is n ). In some cases, this means that you need to separately handle the extreme cases for the first (or last) element.
In this case, it is very easy to implement a method similar to each_cons , but which will give (nil, elem0) for the first element (unlike each_cons , which gives (elem0, elem1) :
module Enumerable def each_with_previous self.inject(nil){|prev, curr| yield prev, curr; curr} self end end
Mladen jablanoviΔ
source share