From: Saynatkari Date: 2005-03-31T08:27:54+09:00 Subject: Re: Syntax sugar idea for loops In data 3/30/2005, "Berger, Daniel" ha scritto: >> -----Original Message----- >> From: pmak@aaanime.net [mailto:pmak@aaanime.net] >> Sent: Wednesday, March 30, 2005 11:30 AM >> To: ruby-talk ML >> Subject: Syntax sugar idea for loops >> >> >> I was working with a proprietary programming language called >> Traction , and I noticed something >> pretty cool they had in their loop constructs. >> >> 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 >> >> This code prints out an HTML table of peoples' names and >> e-mail addresses. The tags alternate with having >> class="row1" and class="row2", allowing every other row to be >> colored differently. >> >> 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 >> >> (In the case of nested loops, they apply to the innermost >> loop.) Maybe Ruby could use this sort of syntax sugar, too? >> So in my example above, there would be a built-in variable >> that replaces my "every_other" variable. > >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 i.first? > row_class = i.even? ? "row1" : "row2" > puts "Last person: #{person} if i.last? >end > >But that would mean making some serious modifications to Enumerable >(wouldn't it?). Not a bad idea, just not worth the added code >maintenance IMHO. Adding Enumerable#step (or maybe Array#step) might not be a bad idea but I do not know how common that usage might be. >Regards, > >Dan E