Ruby:是否有类似 Enumerable#drop 的东西返回枚举器而不是数组?
我有一些大的固定宽度文件,我需要删除标题行。
跟踪迭代器似乎不太惯用。
# 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 的习惯用法是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这稍微更简洁:
或者
This is slightly neater:
or
如果您多次需要它,您可以为
Enumerator
编写一个扩展。If you need it more than once, you could write an extension to
Enumerator
.现在您已经得到了合理的答案,这是一种完全不同的处理方式。
第一次玩时,它既不惯用,也不太直观,但很有趣!
Now that you've gotten reasonable answers, here's a completely different way to handle it.
It's neither idiomatic, nor terribly intuitive the first time through, but it's fun!
在我的脑海中,但我确信通过更多的研究,有一种更优雅的方式
好吧,从头开始......做了一些研究,这可能会更好
Off the top of my head but I'm sure with some more research there's a more elegant way
Okay scratch that... did a bit of research and this might be better
我怀疑这是否惯用,但它很简单。
I doubt that this is idiomatic, but it's simple.
我认为您使用枚举器和 drop(1) 是正确的。由于某些奇怪的原因,虽然 Enumerable 定义了 #drop,但 Enumerator 没有。这是一个有效的 Enumerator#drop:
I think you are right on track with the Enumerator and drop(1). For some odd reason, while Enumerable defines #drop, Enumerator does not. Here is a working Enumerator#drop: