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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With