Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Class Variables?

class Foo
  @@default = "default"

  p instance_variables
  p class_variables

  class << self
    p instance_variables
    p class_variables

    # How do I access the @@default variable here?
  end
end
like image 937
RyanScottLewis Avatar asked Aug 21 '26 05:08

RyanScottLewis


2 Answers

The same way you do it in any other place: @@default.

I'm not sure what p .. is supposed to do (Ruby isn't my native language), but this works

class Foo
  @@default = "default"

  class << self
    puts "#{@@default}"
  end
end
like image 68
Nikita Rybak Avatar answered Aug 22 '26 20:08

Nikita Rybak


This question is kind of interesting because it essentially asks "is there any way for the metaclass to reference its "real" class?

And as far as I can tell, the answer is "no", because all of the "upward" ancestor pointers Ruby keeps also point to metaclasses, and so running class_variables() in one of them will tell you about its class instance variables. So, you have to reference objects by name or just establish a handle before entering the metaclass context...

class Foo
  @@default = "default"
  @@me = self

  p instance_variables
  p class_variables

  class << self
    p instance_variables
    p @@me.class_variables
  end
end
like image 28
DigitalRoss Avatar answered Aug 22 '26 20:08

DigitalRoss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!