List Ruby Object Methods

Published: Monday, October 5, 2020

Greetings, friends! Let's learn how to list methods on a Ruby object! Then, we'll learn how to list out an object's methods without its base class methods.

Suppose we had the following class definition with a single method:

ruby
Copied! ⭐️
class Person
  def display_passion_for_food
    puts 'I love food!!!'
  end
end

Then, we create an instance of this class:

ruby
Copied! ⭐️
nate = Person.new

We can list out all available methods on this class instance using the following command:

ruby
Copied! ⭐️
person.methods

Which outputs the following:

ruby
Copied! ⭐️
[:display_passion_for_food, :pretty_print, :pretty_print_inspect, :pretty_print_instance_variables, :pretty_print_cycle, :instance_variable_set, :instance_variable_defined?, :remove_instance_variable, :instance_of?, :kind_of?, :is_a?, :tap, :instance_variable_get, :public_methods, :instance_variables, :method, :public_method, :define_singleton_method, :public_send, :singleton_method, :extend, :to_enum, :enum_for, :<=>, :===, :=~, :!~, :eql?, :respond_to?, :freeze, :inspect, :object_id, :send, :to_s, :pretty_inspect, :display, :nil?, :hash, :class, :singleton_class, :clone, :itself, :dup, :taint, :yield_self, :untaint, :tainted?, :untrusted?, :untrust, :frozen?, :trust, :methods, :singleton_methods, :protected_methods, :private_methods, :!, :equal?, :instance_eval, :==, :instance_exec, :!=, :__id__, :__send__]

Quite a long list! Where'd all these methods come from? These methods are inherited from the base Object class. You can identify our class instance's parent class by typing the following:

ruby
Copied! ⭐️
nate.class.superclass

Which will output the following:

ruby
Copied! ⭐️
Object

Suppose we wanted to quickly see all methods defined on our class only. Perhaps we're debugging a Rails application and need this information. You can "subtract" the instance methods of the main Object class from our Person instance using the following approach:

ruby
Copied! ⭐️
nate.methods - Object.instance_methods

Where nate is an instance of the class, Person, we created earlier.

Alternatively, you can reference the class, itself:

ruby
Copied! ⭐️
Person.instance_methods - Object.instance_methods

In both cases, you should see the following output:

ruby
Copied! ⭐️
[:display_passion_for_food]

Much cleaner!

This is just a neat little trick I stumbled upon while debugging code at work. I hope it helps!