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