如何编写自己的loop_until? [英] How do I write my own loop_until?
本文介绍了如何编写自己的loop_until?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在练习我的Ruby元编程,并尝试编写自己的循环方法,该方法将处理侦听套接字的大多数丑陋现象,但使程序员有机会指定循环中断条件和某些事情在每个IO.select/sleep周期之后执行.
I'm practicing my Ruby meta-programming and trying to write my own loop method that will handle most of the ugliness in listening to a socket, but give the programmer the chance to specify the loop break condition and a block of things to do after each IO.select/sleep cycle.
我想要写的是这样的:
x = 1
while_listening_until( x == 0 ) do
x = rand(10)
puts x
end
我能够做的是:
def while_listening_until( params, &block )
break_cond = params[ :condition ] || "false"
loop {
#other listening things are happening here
yield
break if params[:binding].eval( break_cond )
}
end
x = 1
while_listening_until( :condition => "x==0", :binding => binding() ) do
x = rand(10)
puts x
end
那么,如何使所有eval
和绑定的丑陋消失?
So, how do I make all that eval
and binding ugliness go away?
推荐答案
这是lambda派上用场的地方:
This is where lambdas are handy:
def while_listening_until( condition, &block )
loop {
#other listening things are happening here
yield
break if condition.call
}
end
x = 1
while_listening(lambda{ x == 0 }) do
x = rand(10)
puts x
end
这篇关于如何编写自己的loop_until?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文