[英]How to find all the methods of a class I have written in Ruby
I have written a Ruby class that contains 3 methods and "includes" methods from other classes. 我编写了一个Ruby类,其中包含3种方法,其他类中的“ includes”方法。 How can I determine the names of the 3 methods I have written?
如何确定我编写的3种方法的名称?
If this class is part of a module, how can I determine the names of the methods I have written ie methods not part of other "include" classes or ancestor classes? 如果此类是模块的一部分,如何确定已编写的方法的名称,即方法不属于其他“包含”类或祖先类的一部分?
Try this: 尝试这个:
MyClass.instance_methods(false)
The false tells it not to include inherited methods. false指示它不包括继承的方法。
Example: 例:
class A
def method1
end
end
class B < A
def method2
end
end
puts B.instance_methods(false)
This outputs method2
. 这输出
method2
。
There is no need to manually exclure the methods of ancestors and mixins. 无需手动排除祖先和混合方法。
To get the list of public methods
that are only part of the class use public_methods(false)
要获取仅属于该类的
public methods
的列表,请使用public_methods(false)
You can get more ways to get methods out of a class instance in the Object
documentation http://ruby-doc.org/core-2.1.0/Object.html# 您可以在
Object
文档http://ruby-doc.org/core-2.1.0/Object.html#中获得更多从类实例中获取方法的方法。
[7] pry(main)> p "".public_methods(false);
[:<=>, :==, :===, :eql?, :hash, :casecmp, :+, :*, :%, :[], :[]=, :insert, :length, :size, :bytesize, :empty?, :=~, :match, :succ, :succ!, :next, :next!, :upto, :index, :rindex, :replace, :clear, :chr, :getbyte, :setbyte, :byteslice, :to_i, :to_f, :to_s, :to_str, :inspect, :dump, :upcase, :downcase, :capitalize, :swapcase, :upcase!, :downcase!, :capitalize!, :swapcase!, :hex, :oct, :split, :lines, :bytes, :chars, :codepoints, :reverse, :reverse!, :concat, :<<, :prepend, :crypt, :intern, :to_sym, :ord, :include?, :start_with?, :end_with?, :scan, :ljust, :rjust, :center, :sub, :gsub, :chop, :chomp, :strip, :lstrip, :rstrip, :sub!, :gsub!, :chop!, :chomp!, :strip!, :lstrip!, :rstrip!, :tr, :tr_s, :delete, :squeeze, :count, :tr!, :tr_s!, :delete!, :squeeze!, :each_line, :each_byte, :each_char, :each_codepoint, :sum, :slice, :slice!, :partition, :rpartition, :encoding, :force_encoding, :b, :valid_encoding?, :ascii_only?, :unpack, :encode, :encode!, :to_r, :to_c, :shellsplit, :shellescape]
您可以通过在任何ruby对象上调用.methods来获取方法列表,但是据我所知,使用mixin样式include不会留下任何面包屑,您可以回溯并找到“实际”方法与“ included”方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.