[ruby-on-rails] How to list all methods for an object in Ruby?

How do I list all the methods that a particular object has access to?

I have a @current_user object, defined in the application controller:

def current_user
  @current_user ||= User.find(session[:user_id]) if session[:user_id]
end

And want to see what methods I have available to me in the view file. Specifically, I want to see what methods a :has_many association provides. (I know what :has_many should provide, but want to check that.)

This question is related to ruby-on-rails ruby

The answer is


What about one of these?

object.methods.sort
Class.methods.sort

Or just User.methods(false) to return only the methods defined within that class.


If You are looking list of methods which respond by an instance (in your case @current_user). According to ruby documentation methods

Returns a list of the names of public and protected methods of obj. This will include all the methods accessible in obj's ancestors. If the optional parameter is false, it returns an array of obj's public and protected singleton methods, the array will not include methods in modules included in obj.

@current_user.methods
@current_user.methods(false) #only public and protected singleton methods and also array will not include methods in modules included in @current_user class or parent of it.

Alternatively, You can also check that a method is callable on an object or not?.

@current_user.respond_to?:your_method_name

If you don't want parent class methods then just subtract the parent class methods from it.

@current_user.methods - @current_user.class.superclass.new.methods #methods that are available to @current_user instance.

To expound upon @clyfe's answer. You can get a list of your instance methods using the following code (assuming that you have an Object Class named "Parser"):

Parser.new.methods - Object.new.methods

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.

module A
  def method1()  end
end
class B
  def method2()  end
end
class C < B
  def method3()  end
end

A.instance_methods                #=> [:method1]
B.instance_methods(false)         #=> [:method2]
C.instance_methods(false)         #=> [:method3]
C.instance_methods(true).length   #=> 43

You can do

current_user.methods

For better listing

puts "\n\current_user.methods : "+ current_user.methods.sort.join("\n").to_s+"\n\n"

Suppose User has_many Posts:

u = User.first
u.posts.methods
u.posts.methods - Object.methods