问题描述
我不确定Ruby中C风格回调的最好方法 - 或者有更好的方法(不像C)。在C中,我会做如下:
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 )
}
一个好的Ruby对等体是什么?基本上我想调用一个传递的类方法,当一个特定的条件满足DoStuff
Whats a good Ruby equivalent? Essentially I want to call a passed in class method, when a certain condition is met within "DoStuff"
推荐答案
这不是惯用的,将是:
def my_callback(a, b, c, status_code)
puts "did stuff with #{a}, #{b}, #{c} and got #{status_code}"
end
def do_stuff(a, b, c, callback)
sum = a + b + c
callback.call(a, b, c, sum)
end
def main
a = 1
b = 2
c = 3
do_stuff(a, b, c, method(:my_callback))
end
习惯的方法是传递一个块而不是一个方法的引用。块对独立方法的一个优点是上下文 - 块是 ,因此它可以引用来自它声明的作用域的变量。这减少了do_stuff需要传递给回调的参数的数量。例如:
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:
def do_stuff(a, b, c, &block)
sum = a + b + c
yield sum
end
def main
a = 1
b = 2
c = 3
do_stuff(a, b, c) { |status_code|
puts "did stuff with #{a}, #{b}, #{c} and got #{status_code}"
}
end
这篇关于如何实现“回调”在Ruby?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!