[英]Dose self.class.class_eval equal to instance_eval?
I want to find out the difference between instance_eval and class_eval,so i did some work。After searching the internet, I figure out something, but there comes an other question I can't understand!When I'm doing this: 我想找出instance_eval和class_eval之间的区别,所以我做了一些工作。在互联网上搜索后,我发现了一些问题,但是还有另一个我无法理解的问题!当我这样做时:
class FindMe
def method_missing method, *args, &block
method = method.to_s
self.class.class_eval <<-EOF, __FILE__, __LINE__
def #{method}
puts "I'm an instance method! I'm #{method}"
end
EOF
send method, *args
end
def self.method_missing method, *args, &block
method = method.to_s
instance_eval <<-HERE, __FILE__, __LINE__
def #{method}
puts "I'm a class method! I'm #{method}"
end
HERE
send method, *args
end
end
FindMe.new.hello
FindMe.hello
I get 我懂了
I'm an instance method! I'm hello
I'm a class method! I'm hello
When I change my code to : 当我将代码更改为:
class FindMe
def method_missing method, *args, &block
method = method.to_s
self.class.class_eval <<-EOF, __FILE__, __LINE__
def #{method}
puts "I'm an instance method! I'm #{method}"
end
EOF
send method, *args
end
def self.method_missing method, *args, &block
method = method.to_s
self.class.class_eval <<-HERE, __FILE__, __LINE__
def #{method}
puts "I'm a class method! I'm #{method}"
end
HERE
send method, *args
end
end
FindMe.new.hello
FindMe.hello
I get the same output, Can any one tell what's going on? 我得到相同的输出,任何人都可以告诉发生了什么吗?
By class_eval
you modify the class, by instance_eval
the current instance only. 通过
class_eval
可以修改类,而instance_eval
则只能修改当前实例。 Look: 看:
▶ class A
▷ def ceval
▷ self.class.class_eval "def on_class ; puts 'On Class' ; end"
▷ end
▷ def ieval
▷ self.instance_eval "def on_instance ; puts 'On Instance' ; end"
▷ end
▷ end
▶ a1 = A.new
#⇒ #<A:0xcf6a87c>
▶ a1.ceval
#⇒ :on_class
▶ a1.ieval
#⇒ :on_instance
▶ a1.on_class
#⇒ On Class
▶ a1.on_instance
#⇒ On Instance
▶ a2 = A.new
#⇒ #<A:0xd0e9f7c>
▶ a2.on_class
#⇒ On Class !!! IT IS DEFINED ON NEWLY CREATED INSTANCE OF A
▶ a2.on_instance
#⇒ NoMethodError: undefined method `on_instance' for #<A:0xd0e9f7c>
The latter fails because we declare on_instance
method on instance a1
, and a2
knows nothing about it. 后者失败是因为我们在实例
a1
上声明了on_instance
方法,而a2
对此一无所知。
See this example, and try explain to yourself: 请参见以下示例,并尝试向自己解释:
class Foo
def a
self.class.class_eval <<-EOS
def x
'This is an instance method.'
end
EOS
end
def b
self.instance_eval <<-EOS
def y
'This is a singleton method.'
end
EOS
end
end
foo1 = Foo.new
foo2 = Foo.new
foo1.a
foo1.b
foo1.x #=> This is an instance method.
foo1.y #=> This is a singleton method.
foo2.x #=> This is an instance method.
foo2.y #=> NoMethodError
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.