From: Gary Wright Date: 2007-04-03T15:31:09+09:00 Subject: Re: Last iteration condition On Apr 3, 2007, at 1:44 AM, Brian Candler wrote: > Try thread around > http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/72518 > for some sample implementations. Building off of Brian's suggestion in that thread, here is a way to provide a 'countdown' as the end of the iteration approaches. Default is to only flag the last item but you can ask for any number of items to be flagged. This is the first time I've found a need for the numeric return value of nonzero? module Enumerable def each_with_countdown(count=0) queue = [] each_with_index do |item,index| if index > (count) yield queue.shift, true end queue.push(item) end queue.each_with_index do |item, index| yield item, (count - index).nonzero? end end end [1,2,3,4,5,6].each_with_countdown(3) { |item, more| case more when TrueClass puts "#{item}" when 3 puts "#{item}, next to next to next to last item!" when 2 puts "#{item}, next to next to last item!" when 1 puts "#{item}, next to last item!" when NilClass puts "#{item}, last item" end } [1,2,3,4,5,6].each_with_countdown(1) { |item, more| puts "#{item}, more: #{more.inspect}" } [1].each_with_countdown { |item, more| puts "#{item}, more: #{more.inspect}" } StringIO.new("line1\nline2\nline3").each_with_countdown do |line, more| if more puts line else puts "last: #{line}" end end Gary Wright