0

我不确定这是否真的可行,但我无法在任何地方找到明确的答案。此外,我发现很难仅用“搜索词”来定义我的问题。所以很抱歉,如果这已经在其他地方得到了回答,我找不到它。

我想知道的是是否可以创建一个 Proc 来保存一个未在定义 Proc 的位置定义的方法。然后我想将该实例放入另一个具有该方法的类中,并使用提供的参数运行该实例。

这是我想要完成但不知道如何完成的示例。

class MyClassA

  # This class does not have the #run method
  # but I want Class B to run the #run method that
  # I invoke from within the Proc within this initializer
  def initialize
    Proc.new { run 'something great' }
  end

end

class MyClassB

  def initialize(my_class_a_object)
    my_class_a_object.call
  end

  # This is the #run method I want to invoke
  def run(message)
    puts message
  end

end

# This is what I execute
my_class_a_object = MyClassA.new
MyClassB.new(my_class_a_object)

产生以下错误

NoMethodError: undefined method  for #<MyClassA:0x10017d878>

而且我想我明白为什么,这是因为它试图run在实例上调用该方法,MyClassA而不是在MyClassB. 但是,有没有办法让run命令调用MyClassBrun实例方法?

4

1 回答 1

2

您的代码有两个问题:

  1. MyClassA.new不返回initialize它的值总是返回一个MyClassA.

  2. 你不能只调用proc,你必须使用该instance_eval方法在上下文中运行它MyClassB

这是您的代码已更正以按您的意愿工作:

class MyClassA    
  def self.get_proc
    Proc.new { run 'something great' }
  end
end

class MyClassB

  def initialize(my_class_a_object)
   instance_eval(&my_class_a_object)
  end

  # This is the #run method I want to invoke
  def run(message)
    puts message
  end

end

# This is what I execute
my_class_a_object = MyClassA.get_proc
MyClassB.new(my_class_a_object) #=> "something great"
于 2010-11-03T21:43:51.157 回答