Where Ruby instance methods, instance variables and singleton methods live

Ruby instance variables live in instances of classes, instance methods live in class objects, and singleton methods live in the singleton class (used to be referred to as the eigenclass).

Instance variables store data associated with instances, so it makes sense for instance variables to live in instances of classes. Here’s an example:

class A
  def initialize
    @cowabunga = 'ninja turtles'
  end
end

obj = A.new
p obj # => #<A:0x007fccf2046f70 @cowabunga="ninja turtles">

Instance methods are shared by all instances of a class, so they must live in the class object.

class Batman
  def m1; end
  def m2; end
end

p Batman.instance_methods(false) # => [:m1, :m2]

Singleton methods are methods for a single object. Singleton methods cannot live in a regular instance because methods can only be stored in class objects. Singleton methods live in the singleton class.

class CatWoman
  class << self
    def purr; end
  end
end

singleton_class = CatWoman.singleton_class
p singleton_class.instance_methods(false) # => [:purr]

Notice that singleton methods are really just instance methods in the singleton class. In Ruby, there are no real class methods – there are instance methods that live in the regular class and instance methods that live in the singleton class.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s