如何编写自己的loop_until?

时间:2013-05-02 16:25:55

标签: ruby metaprogramming

我正在练习我的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和具有约束力的丑陋消失?

1 个答案:

答案 0 :(得分:2)

这就是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