From: Kendall Gifford Date: 2009-06-12T02:35:53+09:00 Subject: Re: Idiomatic way to detect first/last iteration? On Jun 11, 11:18 am, John W Higgins wrote: > > 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 > This is certainly an option in general. However, for my purposes, I should provide more context of my actual situation (instead of my contrived example). I'm using ruby to build a rails application (I know, now this post may become a bit rails specific, but hang with me). Specifically, I'm writing code to generate/render the view of one of my pages (using erb). The gist of it is that I'm outputting a bunch or "rows", 1 for each entry in a collection. However, I need the rendering to be slightly different for the first and last row. I can totally use each_with_index to do this, but I'm hoping for something else. The rails stack provides a "helper" lib method called "cycle" that allows me to elegantly render rows differently based on some repetition cycle (every-other, or every-fifth, etc). The cycle helper allows me to avoid using each_with_index and testing the "index % some_val" for row coloring. I just want to know if there is a clean, idiomatic way, specifically in ruby (not rails library code) to do something similar, detecting the first/last iteration of a collection. I may just end up writing a rails helper to do something to clean it up (and keep my view code clean and low on logic).