8

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

跟踪迭代器似乎不太习惯。

# 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| ... }

Ruby 的成语是什么?

4

6 回答 6

7

稍微整洁一些:

File.open(fname).each_line.with_index do |line, lineno|
  next if lineno == 0
  # ...
end

或者

io = File.open(fname)
# discard the first line
io.gets
# process the rest of the file
io.each_line {|line| ...}
io.close
于 2010-02-04T14:39:12.793 回答
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, …
于 2010-02-04T18:53:17.857 回答
2

现在您已经得到了合理的答案,这是一种完全不同的处理方式。

class ProcStack
  def initialize(&default)
    @block = default
  end
  def push(&action)
    prev = @block
    @block = lambda do |*args|
      @block = prev
      action[*args]
    end
    self
  end
  def to_proc
    lambda { |*args| @block[*args] }
  end
end
#...
process_lines = ProcStack.new do |line, index|
  puts "processing line #{index} => #{line}"
end.push do |line, index|
  puts "skipping line #{index} => #{line}"
end
File.foreach(filename).each_with_index(&process_lines)

第一次通过它既不惯用,也不非常直观,但它很有趣!

于 2010-02-04T18:27:51.510 回答
1

在我的脑海中,但我相信通过更多的研究会有一种更优雅的方式

File.open( filename ).each_line.to_a[1..-1].each{ |line|... }

好的,从头开始......做了一些研究,这可能会更好

File.open( filename ).each_line.with_index.drop_while{ |line,index|  index == 0 }.each{ |line, index| ... }
于 2010-02-04T13:45:40.310 回答
1

我怀疑这是惯用的,但这很简单。

f = File.open(filename)
f.readline
f.each_line do |x|
   #...
end
于 2010-02-04T15:34:52.920 回答
1

我认为您使用 Enumerator 和 drop(1) 是正确的。出于某种奇怪的原因,虽然 Enumerable 定义了 #drop,但 Enumerator 却没有。这是一个有效的枚举器#drop:

  class Enumerator
    def drop(n_arg)
      n = n_arg.to_i # nil becomes zero
      raise ArgumentError, "n must be positive" unless n > 0
      Enumerator.new do |yielder|
        self.each do |val|
          if n > 0
            n -= 1
          else
            yielder << val
          end
        end
      end
    end
  end
于 2013-04-08T21:22:48.413 回答