用于不可查找流的 Ruby 迭代器
我想从 Ruby 中的不可查找流中读取数据记录。我想让用户决定是否应该跳过或读取当前记录。通常你会包含 Enumerable 并提供必要的方法,让它在 Ruby 中拥有迭代器,但在我的例子中,数据可以被跳过,并且只能进行一次迭代,所以我不确定我应该做什么做。
您更喜欢哪一个?
while record = foo.next
if bar
foo.read
else
foo.skip
end
end
或者
foo.each do |record|
if bar
foo.read
else
foo.skip
end
end
I want to read data records from a non-seekable stream in Ruby. I want to leave it up to the user whether the current record should be skipped or read. Usually you would include Enumerable
and provide the necessary methods for it to have an iterator in Ruby, but in my case data can be skipped and only one iteration is possible, so I'm not sure what I should do.
Which one would you prefer?
while record = foo.next
if bar
foo.read
else
foo.skip
end
end
or
foo.each do |record|
if bar
foo.read
else
foo.skip
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
懒评价?
听起来像是惰性评估的一个很好的候选者。
如何向使用惰性求值实现每个访问器的块生成一条记录,并在使用该记录时读取该记录。
如果有很多访问器,您可以生成一个属性方法来检查读取处理是否已完成,如果需要则执行,然后返回记录。
顺便问一下,跳过与阅读的动机是什么?执行速度?如果是这样,我可能只是尝试简单的方法并始终阅读,只是为了看看它是否足够快。
Lazy evaluation?
Sounds like a good candidate for lazy evaluation.
How about yielding a record to the block that implements each accessor with lazy evaluation and reads the record if it gets used.
If there are a lot of accessors, you could just yield an attribute method that checks to see if the read processing has been done, does it if necessary, and then returns the record.
By the way, what's the motivation for skip vs read? Execution speed? If so I might just try it the simple way and always read, just to see if it's fast enough.