简体   繁体   中英

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?

The error thrown is because MySelf.instance_eval('@@name') correctly throws an error. 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.

Check the repl here: https://repl.it/Be0U/0

To set the class variable, use class_variable_set like so:

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM