From: Patrick Hurley Date: 2005-03-31T04:51:06+09:00 Subject: Re: Syntax sugar idea for loops On Thu, 31 Mar 2005 04:37:42 +0900, Eric Hodel wrote: > 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 > > And you could of course do something like (hey is this a valid use for @@vars or is there a better way? -- does Ruby have the C concept of a local static variable?) class Object @@nasty_bad_pseudo_global_hash = Hash.new(true) def alternate(*args) doit = @@nasty_bad_pseudo_global_hash[caller.first] @@nasty_bad_pseudo_global_hash[caller.first] = !doit yield(args) if doit end end (1..10).each do |i| alternate(i) { |x| puts x } end