How to find singleton private methods

I defined the Vehicle module as such

 module Vehicle class <<self def build end private def background end end end 

Calling Vehicle.singleton_methods returns [:build] .

How can I check all the private singleton methods defined by Vehicle ?

+8
ruby eigenclass singleton-methods
source share
1 answer

In Ruby 1.9+, you can simply:

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

In Ruby 1.8, things are a little more complicated.

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

will return all private methods. You can filter most of those declared outside by doing

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

but this is not quite one of them, you need to create a module for this

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

This last one has the unfortunate requirement of creating a module just to throw it away.

+8
source share

All Articles