Eigenclass in ruby

To me, “Eigenclass” is a weird name. Here is the definition of “Eigenclass” from wikipedia:

A hidden class associated with each specific instance of another class.

“Eigen” is a Dutch word, which means “own” or “one’s own”. So “Eigenclass” means the class that class owned by the instance itself.

To open the eigenclass of the object, Ruby provide the following way:

Open Eigenclass
1
2
3
4
5
6
7
foo = Foo.new
class << foo
# do something with the eigenclass of foo
end

Since the in most cases, the purpose that we open a eigenclass is to define singleton methods on specific object. So Ruby provide an easy way to define the singleton method on specific instance:

Shorten saying
1
2
3
4
5
6
7
foo = Foo.new
def foo.some_method
# do something
end

Since “static method” or “class method” is actually the singleton method of a specific class. So this statement is usually used to declare the “class method”.

Besides this simpler statment, we also can open the eigenclass of the class to achieve the same result.
We can write this:

Open eigenclass of the class
1
2
3
4
5
6
7
8
9
10
11
class Foo
class << self
# define class methods
end
# define instance methods
end

Since we’re in the class block, so the “self” indicates the Foo class instance. So we can use class << self; end to open the eigenclass of the class.