From: Brian Adkins Date: 2007-10-26T22:25:01+09:00 Subject: Re: Skip the first invocation e.g. skip_first { foo } On Oct 25, 10:28 pm, mortee wrote: > Brian Adkins wrote: > > Consider the following code: > > > first = true > > 3.times do > > if first > > first = false > > else > > puts 'foo' > > end > > ... > > end > > > I'd like to be able to do the following instead: > > > 3.times do > > skip_first { puts 'foo' } > > ... > > end > > > However, I'm pretty sure that's impossible - especially when you > > consider running the above code twice would require state to be > > initialized twice, so I expect some initialization outside the loop is > > necessary. > > > So, what's the most elegant way to solve this? > > I'd try something along these lines: > > # sets up a binding with a local variable _iteration = 0, and then > # creates a lambda which inherits this binding, and can use the variable > # note that the lambda also inherits any block given to skip_first, > # so it can also yield > > def skip_first(_skip_count = 1) > _iteration = 0 > lambda do |x| > yield x if _iteration >= _skip_count > _iteration += 1 > end > end > > # you can then pass the lambda returned by skip_first to any iterator, > # using the & notation > > 5.times &skip_first {|a| puts a} > 1 > 2 > 3 > 4 So how do you pass the "real" block to the iterator then? The main point of the iteration isn't the code that's skipped on the first iteration, but the main body of the iteration. For example: foo.each do |elem| skip_first do # processing to be skipped the first time # through the loop that may or may not use # elem end # other important processing using elem end