From: Robert Dober Date: 2009-06-12T21:46:07+09:00 Subject: Re: Idiomatic way to detect first/last iteration? On Thu, Jun 11, 2009 at 6: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? > > Specifically, I'm trying to avoid using each_with_index (as shown > below): > > genres = %w{ classical punk rock jazz } > genres.each_with_index do |genre, i| >  desc = "one of my favorites" >  desc = "my absolute favorite" if i.zero? >  desc = "my least fav. of all my favorites" if i + 1 == genres.length >  puts "#{genre} is #{desc}" > end > > I just don't like having to compare an index value (especially as when > detecting the final iteration) and hate even having it as a loop > parameter unless absolutely necessary. I know, I'm picky. Just wanted > to beat the bushes and see if any cool alternatives pop up. > > Kendall streams might give you the abstraction you need --------------- 8< ------------------------ require 'lab419/functional/streams/core' require 'lab419/functional/streams/as-enums' x = %w{a b c a b}.to_stream x.each do | s | p [ s.head, s.tail == EmptyStream ] end ----------------- >8 ---------------- I might implement SimpleStream#first?, SimpleStream#last? and SimpleStream#middle? if I find some spare time, and if anybody needs it ;) I admit however that there is still a little price to pay, you might have noticed that s is a stream and not an element of the stream, but that is just the way streams work. HTH Robert -- Toutes les grandes personnes ont d’abord été des enfants, mais peu d’entre elles s’en souviennent. All adults have been children first, but not many remember. [Antoine de Saint-Exupéry]