tags:

views:

42

answers:

2
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
+2  A: 

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
Nikita Rybak
Well, I feel stupid. Thanks =p
c00lryguy
`p` is a lazy way of writing `puts` :P
david4dev
The method "p" calls `#inspect` and then calls `puts()` on the result. It's more of a debugging method whereas `puts()` is a general-purpose output method.
DigitalRoss
@Nikita, Can you explain how this class variable is accessible in the singleton class? as far as i understand singleton classes and class variables, it shouldn't be :/
banister
@banister I have little theoretical knowledge of Ruby (as I said in the answer), but if you run above code you'll see 'default' at console.
Nikita Rybak
@banister Still, if you consider similar situation in Java (which I do know), accessing static variables from static methods makes sense there.
Nikita Rybak
@Nikita, yes...but in ruby i dont think it makes sense...i can see it it useful, but i cant make sense of it. :) but yes...it does seem to work :)
banister
@banister You mean, that because 'singleton methods' are just instance methods of class object, 'singleton variables' should be instance variables of class object and hence referenced with single '@'? Not sure, may be you could ask a question here about that :)
Nikita Rybak
A: 

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
DigitalRoss