Ruby:有没有像 Enumerable#drop 这样返回枚举器而不是数组的东西? [英] Ruby: Is there something like Enumerable#drop that returns an enumerator instead of an array?
本文介绍了Ruby:有没有像 Enumerable#drop 这样返回枚举器而不是数组的东西?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些固定宽度的大文件,我需要删除标题行.
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| ... }
Ruby 的成语是什么?
What's the Ruby idiom for this?
推荐答案
如果你不止一次需要它,你可以为 Enumerator
编写一个扩展.
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, …
这篇关于Ruby:有没有像 Enumerable#drop 这样返回枚举器而不是数组的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文