How do I write my own loop_until?

血红的双手。 提交于 2019-12-23 05:29:22

问题


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.

What I want to be able to write is something like this:

x = 1
while_listening_until( x == 0 ) do
  x = rand(10)
  puts x
end

What I've been able to make work is:

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

So, how do I make all that eval and binding ugliness go away?


回答1:


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


来源:https://stackoverflow.com/questions/16343103/how-do-i-write-my-own-loop-until

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!