On Tue, Apr 03, 2007 at 03:31:09PM +0900, Gary W. wrote:
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.
Interesting. Maybe it would be cleaner to return nil for all
non-countdown
items, and then n-1, n-2 … 0 as the flag (or n, n-1 … 1). e.g.
require ‘stringio’
module Enumerable
def each_with_countdown(count=1)
queue = []
each do |item|
queue.push(item)
yield queue.shift, nil if queue.size > count
end
queue.each_with_index do |item, index|
yield item, count - index - 1
end
end
end
[1,2,3,4,5,6].each_with_countdown(3) { |item, rem|
case rem
when nil
puts “#{item}”
when 2
puts “#{item}, next to next to last item!”
when 1
puts “#{item}, next to last item!”
when 0
puts “#{item}, last item”
end
}
[1,2,3,4,5,6].each_with_countdown(1) { |item, rem|
puts “#{item}, rem: #{rem.inspect}”
}
[1].each_with_countdown { |item, rem|
puts “#{item}, rem: #{rem.inspect}”
}
StringIO.new(“line1\nline2\nline3”).each_with_countdown do |line, rem|
if rem
puts “last: #{line}”
else
puts line
end
end