Reputation: 23
I have written a Ruby class that contains 3 methods and "includes" methods from other classes. How can I determine the names of the 3 methods I have written?
If this class is part of a module, how can I determine the names of the methods I have written i.e. methods not part of other "include" classes or ancestor classes?
Upvotes: 1
Views: 87
Reputation: 9752
To get the list of public methods
that are only part of the class use 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#
[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]
Upvotes: 1
Reputation: 35783
Try this:
MyClass.instance_methods(false)
The false tells it not to include inherited methods.
Example:
class A
def method1
end
end
class B < A
def method2
end
end
puts B.instance_methods(false)
This outputs method2
.
There is no need to manually exclure the methods of ancestors and mixins.
Upvotes: 4
Reputation: 306
You can get a list of methods by calling .methods on any ruby object, but as far as I know using mixin style includes does not leave any breadcrumbs that you would be able to backtrack and find 'actual' methods vs 'included' methods.
Upvotes: 0