Ruby';s def和实例评估与类评估
我正在阅读编程Ruby 1.9的元编程部分,我很难理解Ruby';s def和实例评估与类评估,ruby,metaprogramming,Ruby,Metaprogramming,我正在阅读编程Ruby 1.9的元编程部分,我很难理解class\u eval/class\u exec与instance\u eval/instance\u exec之间的内部情况 首先,我的理解是,def向self(类对象)的方法表中添加了一个方法: 如果我们使用class\u eval,我们会得到相同的行为: A.class_eval do puts self # => A def bar; 42; end # same as above end A.new.bar #
class\u eval
/class\u exec
与instance\u eval
/instance\u exec
之间的内部情况
首先,我的理解是,def
向self
(类对象)的方法表中添加了一个方法:
如果我们使用class\u eval
,我们会得到相同的行为:
A.class_eval do
puts self # => A
def bar; 42; end # same as above
end
A.new.bar # => 42
但在实例评估
案例中,情况有所不同:
A.instance_eval do
puts self # => A
def baz; 42; end # added to the method table of an anonymous
# singleton class of self, so becomes a class method
end
puts A.baz # => 42
s = 'string'
s.instance_eval do ... end # same behavior, so now def creates an instance method
因此我理解class\u eval
和instance\u eval
之间的功能差异
但是class_eval
和instance_eval
块中的上下文在我看来完全相同——特别是,self
指向相同的对象,局部变量
是相同的。那么,模块内部(内部)发生了什么,使得def
的行为有所不同呢
有什么文件我可以看吗?RDoc支持并且没有帮助。从源代码看,似乎设置了一个单例类对象,而实际上并没有——但在Ruby级别上,这种差异在C代码之外是可见的吗?我认为您的困惑来自这样一个事实,即def不依赖于当前的自我,您可能会认为它是一个有自己规则的“当前类” 以下是你的例子:
class A
# defs here go to A
puts self # => A
class << self
#defs here go to A's eigenclass
end
end
A.class_eval do
#defs here go to A
end
A.instance_eval do
#defs here go to A's eigenclass
end
s = "Hello World"
class << s
#defs here go to s's eigenclass
end
A类
#这里的def去一个
将self#=>A
class只是添加到@krusty.ar的答案中:def
和define\u method
将方法添加到当前的方法定义上下文中(我相信这就是它的名称,我不确定),而不是当前的self
只是在一个模块、类或单例类主体内部,这两者恰好是相同的
但是,例如,在脚本主体(aka top-level)中,self
是main
对象,但是当前的方法定义上下文是object
Hm,我明白了——这是有意义的。有什么方法可以检查Ruby代码中的“当前类”吗?我想在A.instance\u eval
中,您的意思是编写#def这里转到A的特征类
?还是我弄错了?这并不简单,我会在网站上发布一些相关链接answer@krusty.ar:谷歌搜索单例类、元类或特征类。(我看到它被称为all 3)它是一个实例特定的类,位于继承中的实例和实例类之间heirarchy@Matt布里格斯:是的,我知道,我的回答中遗漏了什么吗?
class A
# defs here go to A
puts self # => A
class << self
#defs here go to A's eigenclass
end
end
A.class_eval do
#defs here go to A
end
A.instance_eval do
#defs here go to A's eigenclass
end
s = "Hello World"
class << s
#defs here go to s's eigenclass
end