我是 Ruby 的新手,现在想了解一些关于元编程的知识。 我想返回错过的方法名:
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
最佳答案
在您的 method_missing
中,method_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
您可以在需要或需要时自由使用底层实例变量。
关于ruby - method_missing 中的 attr_accessor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9629634/