首先,虽然 eigentclass 似乎被某些人使用 singleton class 是更常见的术语。 Singleton 类包含 Ruby 中对象的特定于对象的行为。除了这个单例类所属的原始对象之外,您不能创建该类的其他实例。
谈到在不同类型的 eval 中定义方法 this article 介绍了 instance_eval 和 class_eval 中定义的方法的好规则:
Use ClassName.instance_eval to define class methods.
Use ClassName.class_eval to define instance methods.
这几乎描述了这种情况。
关于作为 Class 类的实例的类、作为 Class 类的子类的单例类以及其他一些疯狂的东西(与问题没有太大关系)有很多文章。但是由于您的问题可以很容易地应用于常规对象及其类(并且它使事情更容易解释),所以我决定将其全部删除(不过,您仍然可以在答案的修订历史中看到这些内容)。 em>
让我们看看常规类和该类的实例,看看它们是如何工作的:
class A; end
a = A.new
不同类型eval内部的方法定义:
# define instance method inside class context
A.class_eval { def bar; 'bar'; end }
puts a.bar # => bar
puts A.new.bar # => bar
# class_eval is equivalent to re-opening the class
class A
def bar2; 'bar2'; end
end
puts a.bar2 # => bar2
puts A.new.bar2 # => bar2
定义对象特定的方法:
# define object-specific method in the context of object itself
a.instance_eval { def foo; 'foo'; end }
puts a.foo # => foo
# method definition inside instance_eval is equivalent to this
def a.foo2; 'foo2'; end
puts a.foo2 # => foo2
# no foo method here
# puts A.new.foo # => undefined method `foo' for #<A:0x8b35b20>
现在让我们看看对象a的单例类:
# singleton class of a is subclass of A
p (class << a; self; end).ancestors
# => [A, Object, Kernel, BasicObject]
# define instance method inside a's singleton class context
class << a
def foobar; 'foobar'; end;
end
puts a.foobar # => foobar
# as expected foobar is not available for other instances of class A
# because it's instance method of a's singleton class and a is the only
# instance of that class
# puts A.new.foobar # => undefined method `foobar' for #<A:0x8b35b20>
# same for equivalent class_eval version
(class << a; self; end).class_eval do
def foobar2; 'foobar2'; end;
end
puts a.foobar2 # => foobar2
# no foobar2 here as well
# puts A.new.foobar2 # => undefined method `foobar2' for #<A:0x8b35b20>
现在让我们看看实例变量:
# define instance variable for object a
a.instance_eval { @x = 1 }
# we can access that @x using same instance_eval
puts a.instance_eval { @x } # => 1
# or via convenient instance_variable_get method
puts a.instance_variable_get(:@x) # => 1
现在到class_eval中的实例变量:
# class_eval is instance method of Module class
# so it's not available for object a
# a.class_eval { } # => undefined method `class_eval' for #<A:0x8fbaa74>
# instance variable definition works the same inside
# class_eval and instance_eval
A.instance_eval { @y = 1 }
A.class_eval { @z = 1 }
# both variables belong to A class itself
p A.instance_variables # => [:@y, :@z]
# instance variables can be accessed in both ways as well
puts A.instance_eval { @y } # => 1
puts A.class_eval { @z } # => 1
# no instance_variables here
p A.new.instance_variables # => []
现在,如果您将A 类替换为Class 类,将a 对象替换为Klass 对象(在这种特殊情况下只不过是Class 类的实例)我希望你能得到解释你的问题。如果您仍有疑问,请随时询问。