Ruby中有没有办法打印出Object的公共方法

AKW*_*KWF 2 ruby reflection public-method

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

Ben*_*ret 10

methods,instance_methods,public_methods,private_methods并且protected_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]
Run Code Online (Sandbox Code Playgroud)

如@Marnen所述,动态定义的方法(例如with method_missing)将不会出现在此处.您对这些库存的唯一选择是希望您正在使用的库已有详细记录.

  • 也许您应该将您的示例更改为"''.public_methods`或`[] .public_methods`.对于任何知道Ruby的人来说很明显,你的例子列出了`Array`类对象*本身*响应的方法,而不是*Array`类的实例方法,但它可能会误解新手. (2认同)