ruby - 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 access static var @@name instance_eval/class_eval, or how can assign value outside class?

the error thrown because myself.instance_eval('@@name') correctly throws error. not instance variable, it's class variable. you'll want have myself.class_eval('@@name') on it's own, , it'll work.

check repl here: https://repl.it/be0u/0

to set class variable, use class_variable_set so:

 myself.class_variable_set('@@name', 'graham') 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -