我不确定这是否实际上是可能的,但是我在任何地方都找不到明确的答案。另外,我很难用“搜索词”来定义我的问题。因此,我很抱歉,如果已经在其他地方得到了回答,我找不到它。

我想知道的是,是否有可能创建一个Proc,该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 命令调用 MyClassB' run 实例方法?

有帮助吗?

解决方案

您的代码有两个问题:

  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"
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top