From: Gary Wright Date: 2009-06-12T03:32:53+09:00 Subject: Re: Idiomatic way to detect first/last iteration? On Jun 11, 2009, at 12:43 PM, Kendall Gifford wrote: > Hi there, is there any recognized ruby idiomatic way for detecting > when you're on the first and/or last iteration over a collection? Or, > if not, anyone know of any tricky ways? The following solution uses each_with_index internally but doesn't depend on #first, #last, or #length. On a single item collection it will report 'last' but not 'first'. You'll have to decide if that works in your case. Obviously you could change it to report 'both' for a single item. Gary Wright module Enumerable def each_with_position previous = sigil = Object.new each_with_index { |next_item, index| case index when 0 # do nothing when 1 yield(previous, 'first') else yield(previous, 'middle') end previous = next_item } yield(previous, 'last') unless previous == sigil end end >> [1,2,3,4].each_with_position { |*x| p x } [1, "first"] [2, "middle"] [3, "middle"] [4, "last"] => nil >> [].each_with_position { |*x| p x } => nil >> [1].each_with_position { |*x| p x } [1, "last"] => nil