迭代器的无限收益率

dla*_*lin 4 ruby iterator infinite

我正在努力学习一些红宝石.想象一下,我正在循环并执行一个长时间运行的过程,在这个过程中,我想在必要时获得一个微调器.

所以我能做到:

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"
Run Code Online (Sandbox Code Playgroud)

但我认为做得更干净:

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

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

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

max*_*axg 6

Ruby yield并不像你的例子那样工作.但这可能是一个关闭的好地方:

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

spin = spinner

# start working
print spin.call
# more work
print spin.call
# etc...
Run Code Online (Sandbox Code Playgroud)

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


dla*_*lin 5

我喜欢所有这些建议,但我在标准库中找到了Generator,我认为它更符合我想做的事情:

spinChar=Generator.new{ |g|
  ['|','/','-','\\'].cycle{ |x|
    g.yield x
  }
}
#then
spinChar.next
#will indefinitly output the next character.
Run Code Online (Sandbox Code Playgroud)

array index冻结阵列上具有模数的普通增量似乎是最快的.

弗拉德的线程很漂亮,但不完全是我想要的.而在spinner class单行增量会更好,如果红宝石支持i++GLYPHS[@i++%GLYPHS.length]

spinner closure对于我来说,带推移的Max 似乎有点密集,但结果语法几乎就像这个Generator.至少我认为这是一个关闭proc的句子.

Chuck with_spinner实际上非常接近我想要的,但如果你不需要使用如上所述的Generator,为什么会中断.

瓦迪姆,谢谢你指出这generator将是缓慢的.

"Here's a test of 50,000 spins:"
                   user       system     total       real
"array index"      0.050000   0.000000   0.050000 (  0.055520)
"spinner class"    0.100000   0.010000   0.110000 (  0.105594)
"spinner closure"  0.080000   0.030000   0.110000 (  0.116068)
"with_spinner"     0.070000   0.030000   0.100000 (  0.095915)
"generator"        6.710000   0.320000   7.030000 (  7.304569)
Run Code Online (Sandbox Code Playgroud)


acw*_*acw 5

我认为你走的正确cycle.这样的事情怎么样:

1.8.7 :001 > spinner = ['|','/','-','\\'].cycle
 => #<Enumerable::Enumerator:0x7f111c165790> 
1.8.7 :002 > spinner.next
 => "|" 
1.8.7 :003 > spinner.next
 => "/" 
1.8.7 :004 > spinner.next
 => "-" 
1.8.7 :005 > spinner.next
 => "\\" 
1.8.7 :006 > spinner.next
 => "|" 
Run Code Online (Sandbox Code Playgroud)