0
我不確定這是否實際可行,但我無法在任何地方找到明確的答案。另外,我發現很難僅以「搜索條件」來定義我的問題。所以我很抱歉,如果這已經在別的地方回答,我找不到它。Ruby Proc:從B類中的A類調用方法,並使用B類'方法'
我想知道的是,如果可以創建一個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>
我想我明白爲什麼,這是因爲它試圖調用的MyClassA
實例,而不是一個在MyClassB
的run
方法。但是,有沒有辦法讓run
命令調用MyClassB
的run
實例方法?
謝謝m8!對不起,這是我想要做的一個壞例子。這實際上並不是我遇到的實際問題,但是在這裏添加一個很複雜,所以我寫了一個很快的答案。使用初始化方法犯了錯誤,正如你所說的那樣,當然會返回實例。感謝您的解決方案! :) – 2010-11-04 05:02:43