[英]Why is `instance_eval`/`class_eval` not able to access class variables?
class MySelf
@@name = 'jonathan'
def self.name
@@name
end
end
MySelf.instance_eval {@@name}
MySelf.class_eval {@@name}
both throw: 都抛出:
NameError: uninitialized class variable @@collection in Object
but 但
MySelf.instance_eval {name}
MySelf.class_eval {name}
both work. 两者都可以。
How can I access the static var @@name
with instance_eval
/ class_eval
, or how can I assign a value from outside the class? 如何使用instance_eval
/ class_eval
访问静态var @@name
,或者如何从类外部分配值?
The error thrown is because MySelf.instance_eval('@@name')
correctly throws an error. 引发错误是因为MySelf.instance_eval('@@name')
正确引发了错误。 This is not an instance variable, it's a class variable. 这不是实例变量,而是类变量。 You'll want to have MySelf.class_eval('@@name')
on it's own, and then it'll work. 您需要自己拥有MySelf.class_eval('@@name')
,然后它将起作用。
Check the repl here: https://repl.it/Be0U/0 在此处检查repl: https : //repl.it/Be0U/0
To set the class variable, use class_variable_set
like so: 要设置类变量,请使用class_variable_set
如下所示:
MySelf.class_variable_set('@@name', 'graham')
I think you have to use class instance variable . 我认为您必须使用类实例变量 。
class MySelf
@name = 'jonathan'
def self.name
@name
end
end
MySelf.instance_eval { @name } # => "jonathan"
MySelf.class_eval { @name } # => "jonathan"
Try it, plz. 试试吧,老兄。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.