我有一些大的固定宽度文件,我需要删除标题行.
跟踪迭代器似乎不是很惯用.
# 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的成语是什么?
这有点整洁:
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)
如果你不止一次需要它,你可以写一个扩展名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)
| 归档时间: |
|
| 查看次数: |
4784 次 |
| 最近记录: |