2016-08-22 162 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