[英]Difference between instance_eval and singleton method
Singleton method is a method that is defined only on one instance. 单例方法是仅在一个实例上定义的方法。
foo = Foo.new
def foo.case
#singleton method
end
Doesn't instance_eval
do the same thing? instance_eval
不是一样的吗? Defining a method for a particular instance? 为特定实例定义方法? What is the difference?
有什么不同?
Object# instance_eval
is a method, using which you indeed can define method for an object. Object#
instance_eval
是一个方法,您可以使用它确定对象的方法。
Singleton class is a "place", where the singleton method defined for the object "lives". Singleton类是一个“地方”,其中为对象“生命”定义的单例方法。
So these are two absolutely different things. 所以这些是完全不同的两件事。
The metaprogramming tool
instance_eval
does the same thing right?元编程工具
instance_eval
做了同样的事情吗? Defining a method for a particular instance?为特定实例定义方法?
No. instance_eval
has nothing whatsoever to do with defining methods. 不,
instance_eval
与定义方法没有任何关系。 It evaluates a block in the context of the receiver. 它在接收器的上下文中评估块。 Normally, blocks are lexically scoped, including
self
, a block that is evaluated using instance_eval
is evaluated with self
bound to the receiver of the message. 通常,块是词法范围的,包括
self
,使用instance_eval
计算的块被self
绑定到消息的接收者。
one = Object.new
two = Object.new
def one.my_eval; yield end
instance_variables
# => []
one.my_eval { @ivar_one = 1 }
one.instance_variables
# => []
instance_variables
# => [:@ivar_one]
two.instance_eval { @ivar_two = 2 }
two.instance_variables
# => [:@ivar_two]
So what is really the difference?
那真正的区别是什么?
They are completely unrelated. 它们完全不相关。 It doesn't really make sense to ask about the difference between two unrelated things.
询问两个不相关的事物之间的区别并没有多大意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.