2010-11-03 62 views
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實例,而不是一個在MyClassBrun方法。但是,有沒有辦法讓run命令調用MyClassBrun實例方法?

回答

2

有兩個問題與您的代碼:

  1. MyClassA.new不返回initialize值總是返回的MyClassA一個實例。

  2. 你不能只是調用進程內,你必須使用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" 
+0

謝謝m8!對不起,這是我想要做的一個壞例子。這實際上並不是我遇到的實際問題,但是在這裏添加一個很複雜,所以我寫了一個很快的答案。使用初始化方法犯了錯誤,正如你所說的那樣,當然會返回實例。感謝您的解決方案! :) – 2010-11-04 05:02:43

相關問題