From: John W Higgins Date: 2009-06-12T02:18:31+09:00 Subject: Re: Idiomatic way to detect first/last iteration? --001e680f185cd0dabe046c15c7e2 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit On Thu, Jun 11, 2009 at 9:43 AM, 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. > > One option (not necessarily much prettier) would be to explicitly select out the portions genres = %w{ classical punk rock jazz } puts "My absolute favorite #{genres[0]}" genres[1..-2].each{ |g| puts "Another favorite #{g}" } puts "My least favorite #{genres[-1]}" unless genres.length == 1 John --001e680f185cd0dabe046c15c7e2--