我如何编写自己的loop_until?

我正在练习我的Ruby元编程并试图编写我自己的循环方法来处理监听套接字时的大部分丑陋,但是让程序员有机会指定循环中断条件和一系列事情要做每个IO.select/sleep循环。

我想要写的是这样的:

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和结合丑陋消失?

这就是lambda很方便的地方:

 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