2012-08-27 40 views
8

我已經定義了一個模塊Vehicle像這樣如何找到私人單方法

module Vehicle 
    class <<self 
    def build 
    end 

    private 

    def background 
    end 
    end 
end 

的調用Vehicle.singleton_methods返回[:build]

如何檢查由Vehicle定義的所有私有單例方法?

回答

8

在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] 

這最後一個有創造一個模塊的不幸的要求只是把它扔掉。