2

I want to define a class variable on a singleton class. I checked this program's result:

class C
  class << self
    @@val = 100
  end
end

C.singleton_class.class_variables #=> [], I expect [:@@val]
C.class_variables #=> [:@@val]

I expect the scope of @@val to be the singleton class, isn't it?

Would you tell me how to define a class variable on a singleton class using class << self, and the reason why this program is not correct?

0

2 Answers 2

3

It is because when Ruby parser meets a class variable, the current class is resolved according to the lexical scope.

Cf. http://blog.honeybadger.io/lexical-scoping-and-ruby-class-variables/

Sign up to request clarification or add additional context in comments.

Comments

1

To set the singleton class variable, one might use:

class C
  class << self
    class_variable_set :@@cv, 42
  end
end
C.singleton_class.class_variables #⇒ [:@@cv]
C.singleton_class.class_variable_get :@@cv #⇒ 42

3 Comments

thanks. would you tell me why above program is not correct?. that scope is singleton class, isn't it ?
The more I think about it, the more I am convinced this is ruby parser glitch. The scope is C.singleton_class, yes. Even class C ; class << self ; class << self ; @@ccv = 42 ; end ; end ; end results in setting class variable on C. Probably this is how @ and @@ are handled. It responds to the class opened despite whether it appears inside class method, instance method, or any declaration.
@CarySwoveland I have it on purpose.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.