Prasad Surase
Prasad Surase

Reputation: 6574

Difference between a class and its instance

How does Ruby internally differentiate between a class and its instance like MyClass and obj below? What does it do to allow creation of instances of MyClass but not of obj?

MyClass = Class.new
obj = MyClass.new

Upvotes: 0

Views: 82

Answers (1)

Andrew Marshall
Andrew Marshall

Reputation: 97004

It doesn’t differentiate. MyClass is an instance of Class (in the same way that obj is an instance of MyClass), which implements the new method, and Object does not. It’s pretty much that simple—there’s nothing especially extraordinary happening here, Class#new is much like any other method.

Here we can see the ancestry of each object’s class:

MyClass = Class.new
obj = MyClass.new

MyClass.class.ancestors  #=> [Class, Module, Object, Kernel, BasicObject]
obj.class.ancestors      #=> [MyClass, Object, Kernel, BasicObject]

Upvotes: 2

Related Questions