From: Elliot Temple Date: 2006-07-07T03:36:44+09:00 Subject: Re: A newbie would like some code criticism, please... On Jul 6, 2006, at 7:53 AM, Just Another Victim of the Ambient Morality wrote: > > There's also a pattern that often comes up for me and I would > like some > help with it... > > first = true > list.each do |item| > if first > # do something special for the first case > > first = false > else > # do something else for every other item > end > end > > Is there a better way to do this? i'm not happy with the suggested solutions. i think the inject solution is OK when it works, and next best is each_with_index. but i think worrying about indexes is too low level when we don't actually want to deal with numbers. it's worse when you care about the last iteration and have to worry about off-by-one errors (you need to do something special on list.length-1) what might be nicer is either variable capture in loops (i guess that is rejected because it's too confusing?) or each_with_first_last (with a shorter name). it'd work like: list.each_with_first_last do |item, state| if state.first? #.... elsif state.last? #... else #... end end does anyone have a good idea for what to name this? also what order should the arguments be in? inject is memo,item and each_with_index is item,index... -- Elliot Temple http://www.curi.us/blog/