Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way in Ruby to print out the public methods of an Object

... without including all of the public methods of the generic Object? I mean, other than doing array subtraction. I just want to quickly review what's available to me from an object sometimes without going to the docs.

like image 749
AKWF Avatar asked Feb 03 '26 15:02

AKWF


1 Answers

methods, instance_methods, public_methods, private_methods and protected_methods all accept a boolean parameter to determine if the methods of your object's parents are included.

For example:

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]

As noted by @Marnen, the methods defined dynamically (eg. with method_missing) won't appear here. Your only bet for these ones is hoping that the libraries you're using are well documented.

like image 157
Benoit Garret Avatar answered Feb 05 '26 06:02

Benoit Garret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!