I’m not sure of the best idiom for C style call-backs in Ruby – or if there is something even better ( and less like C ). In C, I’d do something like:
void DoStuff( int parameter, CallbackPtr callback )
{
// Do stuff
...
// Notify we're done
callback( status_code )
}
Whats a good Ruby equivalent? Essentially I want to call a passed in class method, when a certain condition is met within “DoStuff”
The ruby equivalent, which isn’t idiomatic, would be:
The idiomatic approach would be to pass a block instead of a reference to a method. One advantage a block has over a freestanding method is context – a block is a closure, so it can refer to variables from the scope in which it was declared. This cuts down on the number of parameters do_stuff needs to pass to the callback. For instance: