簡體   English   中英

有沒有辦法只獲得Ruby類的類方法

[英]is there a way to get only a Ruby class' class methods

我用:

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

但是有沒有辦法得到類方法:

1.9.3-p448 :058 > Object.class_methods

我知道我可以:

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

但是有辦法直接獲得它們嗎? 另外,除了后者中的類方法之外,還有什么可能嗎?

謝謝

klass.methods給出了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)給出了類方法klass被上直接定義klass

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

Object.singleton_class.instance_methods

這應該可以解決問題:

YourObject.class.methods

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM