MrPizzaFace
MrPizzaFace

Reputation: 8086

How to get a list of ONLY my available methods in IRB?

Say I load some code into irb like the following:

class MyClass
  def m 
    #... something
  end
  def a
    #... something
  end
end

How can I get a list of only my available methods? If I run MyClass.new.methods I get back all of the available instance methods.

I would like to just see: :m, :a

Additionally, what if my methods aren't wrapped in a class?

def x 
  #... something
end
def z
  #... something
end

How do I see what's available? Calling self.methods (running: methods) doesn't even list my methods.

Upvotes: 2

Views: 470

Answers (2)

David Grayson
David Grayson

Reputation: 87541

This is a little trick that I often use, especially if I am trying to work with an object from a library I did not write:

obj = MyClass.new
obj.methods.sort - 0.methods   # => [:a, :m]

The number 0 has a small set of methods that are mostly just standard Ruby stuff you don't want to see. You could do Object.new instead of 0 and that would be better because you would be able to see methods like succ, but it would be more typing.

The advantage of this over MyClass.instance_methods(false) is that it shows methods included from superclasses, methods included from modules, and methods that were defined dynamically. Also, you typically have an object that you are inspecting rather than a class.

Upvotes: 1

Arup Rakshit
Arup Rakshit

Reputation: 118299

Do as below using Module#instance_methods:

Returns an array containing the names of the public and protected instance methods in the receiver. For a module, these are the public and protected methods; for a class, they are the instance (not singleton) methods. With no argument, or with an argument that is false, the instance methods in mod are returned, otherwise the methods in mod and mod’s superclasses are returned.

class MyClass
  def m 
    #... something
  end
  def a
    #... something
  end
end
MyClass.instance_methods(false)
# => [:m, :a]

If you defined methods on top level like below, they will become private instance methods of the Object class. So I would use then Module#private_instance_methods

Returns a list of the private instance methods defined in mod. If the optional parameter is not false, the methods of any ancestors are included.

def x 
  #... something
end
def z
  #... something
end

Object.private_instance_methods(false)
# => [:x, :z]

Upvotes: 1

Related Questions