我不确定这是否真的可行,但我无法在任何地方找到明确的答案。此外,我发现很难仅用“搜索词”来定义我的问题。所以很抱歉,如果这已经在其他地方得到了回答,我找不到它。
我想知道的是是否可以创建一个 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
实例方法?