From: Gregory Brown Date: 2009-01-29T14:51:28+09:00 Subject: Re: Real life use of each_cons? On Thu, Jan 29, 2009 at 12:19 AM, Mischa Fierer wrote: > Hello, > > I've been going through the enumerable/enumerator methods that I'm > unfamiliar with and came across each_cons. Apart from a post by a guy > who wasn't sure where it was even defined, I have only come across one > use of it in the wild: > > (From Prawn) > > def polygon(*points) > move_to points[0] > (points << points[0]).each_cons(2) do |p1,p2| > line_to(*p2) > end > end > > > Does anyone have any ideas on other cases where each_cons would be > useful? Or perhaps insight into why it's in Ruby? I think you may have been confused by my ugly code there. I have replaced it with: def polygon(*points) move_to points[0] (points[1..-1] << points[0]).each do |point| line_to(*point) end end The reason why it's not needed is because we draw the lines from point to point. But if we were drawing them segment by segment, it'd make sense. >> [[1,2],[3,4],[5,6],[1,2]].each_cons(2) { |a| p a } [[1, 2], [3, 4]] [[3, 4], [5, 6]] [[5, 6], [1, 2]] I imagine I had refactored a line p1, p2 call down to just line_to(p2) without fixing the each_cons()... sorry about that. In general each_cons is useful when you need a sliding window of size n across a dataset. -greg -- Technical Blaag at: http://blog.majesticseacreature.com Non-tech stuff at: http://metametta.blogspot.com "Ruby Best Practices" Book now in O'Reilly Roughcuts: http://rubybestpractices.com