2012-03-09 39 views
1

我很新的Ruby和現在試圖瞭解一些有關的元編程。 我要回錯過的方法名稱:attr_accessor中的method_missing

class Numeric 

    attr_accessor :method_name 

    def method_missing(method_id) 
    method_name = method_id.to_s 
    self 
    end 

    def name 
    method_name 
    end 

end 

10.new_method.name #this should return new_method, but returns nil 

回答

3

裏面你method_missingmethod_name被解釋爲一個局部變量,而不是你所期望的method_missing=賦值函數方法。如果您明確添加的接收器,那麼你會得到你想要的東西:

def method_missing(method_id) 
    self.method_name = method_id.to_s 
    self 
end 

或者,你可以分配給@method_name實例變量:

def method_missing(method_id) 
    @method_name = method_id.to_s 
    self 
end 

attr_accessor宏只是增加了兩種方法,你這麼attr_accessor :p是簡寫本:

def p 
    @p 
end 
def p=(v) 
    @p = v 
end 

你自由了,當你想要或需要使用底層的實例變量。

+0

的感謝!它現在絕對清晰 – dmitry 2012-03-09 08:53:45