ruby - 如何找到私有(private)单例方法

标签 ruby singleton-methods eigenclass

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

module Vehicle
  class <<self
    def build
    end

    private

    def background
    end
  end
end

调用 Vehicle.singleton_methods 返回 [:build]

如何检查 Vehicle 定义的所有私有(private)单例方法?

最佳答案

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

Vehicle.singleton_class.private_instance_methods(false)
#=> [:background]

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

Vehicle.private_methods
#=> [:background, :included, :extended, :method_added, :method_removed, ...]

将返回所有私有(private)方法。您可以通过以下方式过滤大部分在外部声明的内容

Vehicle.private_methods - Module.private_methods
#=> [:background, :append_features, :extend_object, :module_function]

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

Vehicle.private_methods - Module.new.private_methods
#=> [:background]

最后一个有一个不幸的要求,即创建一个模块只是为了丢弃它。

关于ruby - 如何找到私有(private)单例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12135724/

相关文章:

ruby-on-rails - 如何根据对象与其他对象属性的关系设置对象的属性?

objective-c - 帮助理解返回单例的类方法

Ruby eigenclass(单例类)创建了吗?为了哪个?

ruby-on-rails - Ruby on Rails 中的@变量

ruby-on-rails - 在 Rails 中更新/增加值时的数据完整性

Android:是否可以在 Activity 和服务之间共享 GoogleApiClient?

Ruby 类 << abcd 语法

ruby - 一个类和该类在Ruby中的单例之间有什么区别?

Ruby 特征类模式 - 要求澄清

ruby-on-rails - Ruby on Rails - 数组中的 Validates_inclusion_of