我定义了一个称为 Vehicle
的模块,就像这样:
module Vehicle
class <<self
def build
end
private
def background
end
end
end
调用Vehicle.singleton_methods
将返回[:build]
。
我如何检查Vehicle
定义的所有私有单例方法?
我定义了一个称为 Vehicle
的模块,就像这样:
module Vehicle
class <<self
def build
end
private
def background
end
end
end
调用Vehicle.singleton_methods
将返回[:build]
。
我如何检查Vehicle
定义的所有私有单例方法?
在 Ruby 1.9+ 中,您可以简单地执行:
Vehicle.singleton_class.private_instance_methods(false)
#=> [:background]
在 Ruby 1.8 中,情况会更加复杂。Vehicle.private_methods
#=> [:background, :included, :extended, :method_added, :method_removed, ...]
将返回所有私有方法。您可以通过执行以下操作来过滤大多数在外部声明的方法:
Vehicle.private_methods - Module.private_methods
#=> [:background, :append_features, :extend_object, :module_function]
但是那样不能完全清除它们,你需要创建一个模块来完成这个任务
Vehicle.private_methods - Module.new.private_methods
#=> [:background]
这个最后一个不幸的要求是必须创建一个模块然后扔掉它。