迭代器的无限收益率 [英] Infinite yields from an iterator

查看:157
本文介绍了迭代器的无限收益率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习一些红宝石。
想象一下,我正在循环并进行一个长时间运行的过程,在这个过程中,我希望在必要时获得一个微调器。

I'm trying to learn some ruby. Imagine I'm looping and doing a long running process, and in this process I want to get a spinner for as long as necessary.

所以我可以执行:

a=['|','/','-','\\']
aNow=0
# ... skip setup a big loop
print a[aNow]
aNow += 1
aNow = 0 if aNow == a.length
# ... do next step of process
print "\b"

但我觉得这样做会更干净:

But I thought it'd be cleaner to do:

def spinChar
  a=['|','/','-','\\']
  a.cycle{|x| yield x}
end
# ... skip setup a big loop
print spinChar
# ... do next step of process
print "\b"

当然,spinChar调用想要一个块。如果我给它一个块,它将无限期挂起。

Of course the spinChar call wants a block. If I give it a block it'll hang indefinitely.

我怎样才能得到这个块的下一个?

How can I get just the next yeild of this block?

推荐答案

Ruby的 yield 不能按照您的示例的方式工作。但这可能是关闭的好地方:

Ruby's yield does not work in the way your example would like. But this might be a good place for a closure:

def spinner()
  state = ['|','/','-','\\']
  return proc { state.push(state.shift)[0] }
end

spin = spinner

# start working
print spin.call
# more work
print spin.call
# etc...

在实践中,我认为这个解决方案对于自己的好处可能过于聪明,但理解 Proc 无论如何都可能有用。

In practice I think this solution might be too "clever" for its own good, but understanding the idea of Procs could be useful anyhow.

这篇关于迭代器的无限收益率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆