Ruby:有类似于Enumerable#drop的东西会返回一个枚举器而不是一个数组吗?

Sam*_*son 8 ruby enumerable

我有一些大的固定宽度文件,我需要删除标题行.

跟踪迭代器似乎不是很惯用.

# 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| ... }
Run Code Online (Sandbox Code Playgroud)

这个Ruby的成语是什么?

gle*_*man 7

有点整洁:

File.open(fname).each_line.with_index do |line, lineno|
  next if lineno == 0
  # ...
end
Run Code Online (Sandbox Code Playgroud)

要么

io = File.open(fname)
# discard the first line
io.gets
# process the rest of the file
io.each_line {|line| ...}
io.close
Run Code Online (Sandbox Code Playgroud)


Deb*_*ski 5

如果你不止一次需要它,你可以写一个扩展名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, …
Run Code Online (Sandbox Code Playgroud)