Search code examples
rubyclass-variables

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?


Solution

  • 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')