用于不可查找流的 Ruby 迭代器

发布于 2024-09-25 14:29:19 字数 365 浏览 6 评论 0原文

我想从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

背叛残局 2024-10-02 14:29:19

懒评价?

听起来像是惰性评估的一个很好的候选者。

如何向使用惰性求值实现每个访问器的块生成一条记录,并在使用该记录时读取该记录。

如果有很多访问器,您可以生成一个属性方法来检查读取处理是否已完成,如果需要则执行,然后返回记录。

foo.each do |record_manager|
  if bar
    puts record_manager.get.field1 # get does foo.read, whatever that does
    puts record_manager.get.field2 # just returns the processed object this time
  else
    # each() will do .skip() if no get() was called
  end
end

顺便问一下,跳过与阅读的动机是什么?执行速度?如果是这样,我可能只是尝试简单的方法并始终阅读,只是为了看看它是否足够快。

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.

foo.each do |record_manager|
  if bar
    puts record_manager.get.field1 # get does foo.read, whatever that does
    puts record_manager.get.field2 # just returns the processed object this time
  else
    # each() will do .skip() if no get() was called
  end
end

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文