如何实现“回调"在红宝石? [英] How to implement a "callback" in Ruby?

查看:30
本文介绍了如何实现“回调"在红宝石?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定 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"

推荐答案

ruby​​ 等价物(不是惯用的)是:

The ruby equivalent, which isn't idiomatic, would be:

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

这篇关于如何实现“回调"在红宝石?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆