How do I write my own loop_until?

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?

Answers


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

Need Your Help

Can I stop a service synchronously?

android service

I need to stop a pair of services just before I delete a database. The services are accessing the database, and if they are not stopped, the app will crash.

PHP RecursiveDirectoryIterator

php scandir

I want to do a RecursiveDirectoryIterator on a set of folders in a directory, say ./temp and then list the files in each folder according to the name of the folder.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.