鉴于 self 指的是调用 instance_eval 的对象,在 instance_eval 块中使用 self 进行方法定义有区别吗?
Z.instance_eval do
def x
end
def self.y
end
end
> Z.x
=> nil
> Z.y
=> nil
鉴于 self 指的是 Z,self 似乎是多余的。
鉴于 self 指的是调用 instance_eval 的对象,在 instance_eval 块中使用 self 进行方法定义有区别吗?
Z.instance_eval do
def x
end
def self.y
end
end
> Z.x
=> nil
> Z.y
=> nil
鉴于 self 指的是 Z,self 似乎是多余的。
没有区别。正是出于您在问题中解释的原因。
这是一个冗余使用self的例子。在调用方法而不是定义方法时更常见的是:
class Donald
def x
end
def y
self.x # <-- `self` is redundant. We could just call `x` directly.
end
end
但是,如果您能原谅我的示例的荒谬性,那么能够显式地声明对象(即使它是self)有时会很有用。考虑:
class Y; end
class Z; end
Z.instance_eval do
def random_class
rand > 0.5 ? Y : self
end
def random_class.x
end
end
在这里,random_class在运行时评估 - 因此代码在语法上是有效的,即使self可能是多余的。