On Mon, Jun 23, 2003 at 12:49:22AM +0900, Shashank Date wrote:
> Since Ruby is a language with class ;-) I came up with this more
> "classic" (generic) solution:
> 
> #----------------------------------------------------------------
> class Array
>   def skip(n=0,from=0)
>     raise "Cannot skip negative elements" if n < 0
>     0.step(self.length-1,n+1){|i| yield(self[i+from]) if self[i+from]}
>   end
> end
> 
> IO.readlines("junk.txt").skip(1){|line| puts line}
> #----------------------------------------------------------------

A better, more generic solution would not use a[b] to index array elements.
If you limit yourself to using only 'each' then it would be compatible with
all classes which mix in Enumerable. Something like this:

module Enumerable
  def each_skip(n=0, from=0)
    skip = from
    each do |item|
      if skip > 0
        skip -= 1
        next
      end
      yield item
      skip = n
    end
  end
end

Now, you can use this directly on the IO object - you don't even have to
read the lines into an array first (although it works on arrays as well). If
you have a file with a million lines then that makes quite a difference :-)

File.open("junk.txt").each_skip(1) {|line| puts line}
  
Regards,

Brian.