2016-08-22 210 views
0

塊作用域我創造了一些類紅寶石 - 裏法

class Book 
    def perform 
    yield 
    end 
end 

然後我要打電話,它將調用method1method2塊。然而,這兩種方法都沒有定義,我不想定義它們。取而代之的是,我想打電話給method_missing的,但我得到: undefined local variable or method 'method1' for main:Object (NameError)

book = Book.new 
book.perform do 
    method1 
    method2 
end 

我應該怎麼辦呢?

回答

1

爲了做到你的要求,我相信你需要重新定義method_missing像這樣:

class Book 
    def perform 
    yield 
    end 
end 

def method_missing(methodname, *args) 
    puts "#{methodname} called" 
end 

book = Book.new 
book.perform do 
    method1 
    method2 
end 

#=> 
#method1 called 
#method2 called 
+0

偉大的答案,我試圖覆蓋類範圍內的method_missing和它引起我沒工作 – mike927