Reputation: 13
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?
Upvotes: 0
Views: 82
Reputation: 35531
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
Upvotes: 2