Ruby中是否有一种方法可以打印出Object的公共方法

…不包括通用Object的所有公共方法? 我的意思是,除了做数组减法。 我只是想快速回顾一下对象有时可以使用的内容,而无需访问文档。

methodsinstance_methodspublic_methodsprivate_methodsprotected_methods都接受布尔参数来确定是否包含对象父项的方法。

例如:

 ruby-1.9.2-p0 > class MyClass < Object; def my_method; return true; end; end; ruby-1.9.2-p0 > MyClass.new.public_methods => [:my_method, :nil?, :===, :=~, :!~, :eql?, :hash, :<=>, :class, :singleton_class, :clone, :dup, :initialize_dup, :initialize_clone, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :freeze, :frozen?, :to_s, :inspect, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :instance_variables, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :instance_of?, :kind_of?, :is_a?, :tap, :send, :public_send, :respond_to?, :respond_to_missing?, :extend, :display, :method, :public_method, :define_singleton_method, :__id__, :object_id, :to_enum, :enum_for, :==, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__] ruby-1.9.2-p0 > MyClass.new.public_methods(false) => [:my_method] 

如@Marnen所述,动态定义的方法(例如,使用method_missing )将不会出现在此处。 您对这些库存的唯一选择是希望您使用的库具有良好的文档记录。

这是你要找的结果吗?

 class Foo def bar p "bar" end end p Foo.public_instance_methods(false) # => [:bar] 

ps我希望这不是你追求的结果:

 p Foo.public_methods(false) # => [:allocate, :new, :superclass] 

如果有的话,它将不会非常有用:由于Ruby能够通过动态元编程来伪造方法,因此公共方法通常不是您唯一的选择。 所以你不能真正依赖instance_methods告诉你很多它是有用的。

我开始尝试在https://github.com/bf4/Notes/blob/master/code/ruby_inspection.rb中记录所有这些检查方法。

如其他答案所述:

 class Foo; def bar; end; def self.baz; end; end 

首先,我喜欢对方法进行排序

 Foo.public_methods.sort # all public instance methods Foo.public_methods(false).sort # public class methods defined in the class Foo.new.public_methods.sort # all public instance methods Foo.new.public_methods(false).sort # public instance methods defined in the class 

有用的提示Grep找出你的选择

 Foo.public_methods.sort.grep /methods/ # all public class methods matching /method/ # ["instance_methods", "methods", "private_instance_methods", "private_methods", "protected_instance_methods", "protected_methods", "public_instance_methods", "public_methods", "singleton_methods"] Foo.new.public_methods.sort.grep /methods/ # ["methods", "private_methods", "protected_methods", "public_methods", "singleton_methods"] 

另请参阅https://stackoverflow.com/questions/123494/whats-your-favourite-irb-trick