What is ‘Class Definition’ In Ruby

2.2 Class and Module Definitions are Constant Assignments

Let’s suppose the following snippet creates a class (rather than reopening it):

class C

Ruby creates a constant C in Object and stores in that constant a class object. The name of the class instance is “C”, a string, named after the constant.

That is,

class Project < ApplicationRecord

performs a constant assignment equivalent to

Project = Class.new(ApplicationRecord)

including setting the name of the class as a side-effect:

Project.name # => "Project"

Constant assignment has a special rule to make that happen: if the object being assigned is an anonymous class or module, Ruby sets the object’s name to the name of the constant.

From then on, what happens to the constant and the instance does not matter. For example, the constant could be deleted, the class object could be assigned to a different constant, be stored in no constant anymore, etc. Once the name is set, it doesn’t change.

Similarly, module creation using the module keyword as in

module Admin

performs a constant assignment equivalent to

Admin = Module.new

including setting the name as a side-effect:

Admin.name # => "Admin"





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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s