listing methods of class and object (instance)

Posted . Visible to the public.
class Myclass
  def one
    puts "one is called"
  end
end    

ss = Myclass.new

puts Myclass.methods 
# returns array of methods for the class. Includes both class and instance methods and methods inherited from parents.
puts Myclass.instance_methods
# returns array of instance methods for the class
puts ss.methods
# returns array of methods which can be called on the instance. same result as above.
puts Myclass.instance_methods(false)
# returns array of instance methods excluding inherited methods

To check if a method can be called on an object / class use

ss.respond_to? :method_name 
#returns true if the method can be called else false. 
Myclass.respond_to? :method_name

To get the class hierarchy of a given class use

Myclass.ancestors
# returns an array of parent classes for a given class.
Sandheep
Last edit
Posted by Sandheep to Sandheep's deck (2013-04-26 06:24)