Search code examples
rubyenumerable

Ruby: Is there something like Enumerable#drop that returns an enumerator instead of an array?


I have some big fixed-width files and I need to drop the header line.

Keeping track of an iterator doesn't seem very idiomatic.

# This is what I do now.
File.open(filename).each_line.with_index do |line, idx|
  if idx > 0
     ...
  end
end

# This is what I want to do but I don't need drop(1) to slurp
# the file into an array.
File.open(filename).drop(1).each_line do { |line| ... }

What's the Ruby idiom for this?


Solution

  • If you need it more than once, you could write an extension to Enumerator.

    class Enumerator
      def enum_drop(n)
        with_index do |val, idx|
          next if n == idx
          yield val
        end
      end
    end
    
    File.open(testfile).each_line.enum_drop(1) do |line|
      print line
    end
    
    # prints lines #1, #3, #4, …