Foo = Class.new
Foo.class_eval do
def class_bar
"class_bar"
end
end
Foo.instance_eval do
def instance_bar
"instance_bar"
end
end
Foo.class_bar #=> undefined method ‘class_bar’ for Foo:Class
Foo.new.class_bar #=> "class_bar"
Foo.instance_bar #=> "instance_bar"
Foo.new.instance_bar #=> undefined method ‘instance_bar’ for #<Foo:0x7dce8>
仅根据方法的名称,I would expect class_eval to allow you to add a class method to Foo and instance_eval to allow you to add an instance method to Foo. But they seem to do the opposite.
在上面的例子中,如果在Foo类上调用class_-bar,就会得到一个未定义的方法错误,如果在Foo返回的实例上调用instance_-bar.新的,你也会得到一个未定义的方法错误.这两个错误似乎都与class_eval和instance_eval应该做什么的直观理解相矛盾.
What is really the difference between these methods?
class_eval人的文件:
mod.class_eval(string [, filename [, lineno]]) => obj
Evaluates the string or block in the context of mod. This can be used to add methods to a class.
instance_eval人的文件:
obj.instance_eval {| | block } => obj
Evaluates a string containing Ruby source code, or the given block, within the context of the receiver (obj). In order to set the context, the variable self is set to obj while the code is executing, giving the code access to obj’s instance variables.