0

我想将一个类方法作为参数传递给另一个对象调用它,即

do_this(Class.method_name)

接着:

def do_this(class_method)
  y = class_method(local_var_x)
end

我能看到的唯一方法是将其作为字符串传递并使用 eval,或者将类和方法作为字符串传递,然后进行常量化并发送。eval 的缺点似乎是速度和调试?

有没有更简单的方法来做到这一点?

编辑:

很好的答案,但意识到我问的问题略有错误,想使用方法未传递的参数。

4

2 回答 2

3

我建议采用类似于您提出的第二种解决方案的方法。

do_this(Class.method(:name), x)

接着:

def do_this(method, x)
   y = method.call(x)
end

另请参阅 的文档Object#method

于 2013-02-11T20:30:05.890 回答
1

考虑使用 proc 对象:

def do_this(myproc)
    y = myproc.call
end

接着

do_this( Proc.new { klass.method(x) } )

尽管您还应该考虑使用块,这更像是 ruby​​ 风格。那看起来像:

def do_this
   y = yield
end

并通过以下方式致电:

do_this { klass.method(x) }
于 2013-02-11T20:39:15.937 回答