From: Eric Hodel Date: 2005-03-31T04:37:42+09:00 Subject: Re: Syntax sugar idea for loops On 30 Mar 2005, at 11:23, Berger, Daniel wrote: >> From: pmak@aaanime.net [mailto:pmak@aaanime.net] >> >> Consider the following Ruby code: >> >> every_other = true >> people.each do |person| >> every_other = !every_other >> row_class = every_other ? 'row1' : 'row2' >> puts "#{person.name} >> #{person.email}" >> end >> >> Consider these two lines of the code, though: >> >> every_other = true >> every_other = !every_other >> >> These lines could be replaced by syntax sugar. Traction has >> the following "Special Loop Tags": >> >> : true if this is the first iteration of the loop >> true if this is not the first or last >> iteration of the loop >> true if this is an odd iteration >> : true if this is the last iteration of the loop > > I think Enumerable#each_with_index largely eliminates the need for such > syntactic sugar. Consider: > > people.each_with_index do |person, i| > puts "First person: #{person}" if i == 0 > row_class = i%2 == 0 ? "row1" : "row2" > puts "#{person.name} > puts "Last person: #{person}" if i == people.length - 1 > end > > I suppose you could extend Fixnum within a loop to include extra > methods > so that you could do something like this: people.each_with_index do |person, i| puts "First person: #{person} if person == people.first row_class = i.even? ? "row1" : "row2" puts "Last person: #{person} if person == people.last end How about that? -- Eric Hodel - drbrain@segment7.net - http://segment7.net FEC2 57F1 D465 EB15 5D6E 7C11 332A 551C 796C 9F04