如何找到私有单例方法

Mik*_*ord 9 ruby singleton-methods eigenclass

我已经定义了Vehicle这样的模块

module Vehicle
  class <<self
    def build
    end

    private

    def background
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

致电Vehicle.singleton_methods退货[:build].

如何检查定义的所有私有单例方法Vehicle

And*_*all 10

在Ruby 1.9+中,您可以简单地执行以下操作:

Vehicle.singleton_class.private_instance_methods(false)
#=> [:background]
Run Code Online (Sandbox Code Playgroud)

在Ruby 1.8中,事情有点复杂.

Vehicle.private_methods
#=> [:background, :included, :extended, :method_added, :method_removed, ...]
Run Code Online (Sandbox Code Playgroud)

将返回所有私有方法.您可以通过执行过滤大部分在外部声明的内容

Vehicle.private_methods - Module.private_methods
#=> [:background, :append_features, :extend_object, :module_function]
Run Code Online (Sandbox Code Playgroud)

但是这并没有完全解决所有问题,你必须创建一个模块来做到这一点

Vehicle.private_methods - Module.new.private_methods
#=> [:background]
Run Code Online (Sandbox Code Playgroud)

最后一个不幸的要求是创建一个模块只是为了扔掉它.