timpone
timpone

Reputation: 19929

is there a way to get only a Ruby class' class methods

I use:

1.9.3-p448 :057 > Object.methods
 => 270 
1.9.3-p448 :058 > Object.instance_methods
 => 153

but is there a way to just get class methods like:

1.9.3-p448 :058 > Object.class_methods

I know I could:

1.9.3-p448 :057 > Object.methods - Object.instance_methods

but is there a way to just get them directly? Also, is there anything it could be besides a class method in the latter?

thx

Upvotes: 1

Views: 92

Answers (3)

matt9986
matt9986

Reputation: 21

This should do the trick:

YourObject.class.methods

Upvotes: 0

sawa
sawa

Reputation: 168081

klass.methods gives the class methods for class klass.

Dir.methods
# => [:open, :foreach, :entries, :chdir, :getwd, :pwd, :chroot, :mkdir, :rmdir,
:delete, :unlink, :home, :glob, :[], :exist?, :exists?, :allocate, :new,
:superclass, :freeze, :===, :==, :<=>, :<, :<=, :>, :>=, :to_s, :inspect,
:included_modules, :include?, :name, :ancestors, :instance_methods,
:public_instance_methods, :protected_instance_methods, :private_instance_methods,
:constants, :const_get, :const_set, :const_defined?, :const_missing,
:class_variables, :remove_class_variable, :class_variable_get,
:class_variable_set, :class_variable_defined?, :public_constant,
:private_constant, :module_exec, :class_exec, :module_eval, :class_eval,
:method_defined?, :public_method_defined?, :private_method_defined?,
:protected_method_defined?, :public_class_method, :private_class_method,
:autoload, :autoload?, :instance_method, :public_instance_method, :nil?, :=~,
:!~, :eql?, :hash, :class, :singleton_class, :clone, :dup, :taint, :tainted?,
:untaint, :untrust, :untrusted?, :trust, :frozen?, :methods, :singleton_methods,
:protected_methods, :private_methods, :public_methods, :instance_variables,
:instance_variable_get, :instance_variable_set, :instance_variable_defined?,
:remove_instance_variable, :instance_of?, :kind_of?, :is_a?, :tap, :send,
:public_send, :respond_to?, :extend, :display, :method, :public_method,
:define_singleton_method, :object_id, :to_enum, :enum_for, :equal?, :!, :!=,
:instance_eval, :instance_exec, :__send__, :__id__]

klass.methods(false) gives the class methods for klass that are directly defined on klass.

Dir.methods(false)
# => [:open, :foreach, :entries, :chdir, :getwd, :pwd, :chroot, :mkdir, :rmdir,
:delete, :unlink, :home, :glob, :[], :exist?, :exists?]

Upvotes: 3

Jimmy
Jimmy

Reputation: 37081

Object.singleton_class.instance_methods

Upvotes: 2

Related Questions