0

For instance:

class MyClass
    @@var1 = '123456'
    def self.var1
        @@var1
    end

    class << self
        attr_accessor :var2
        def self.initialize
          self.var2 = 7890
        end
    end

end

 p MyClass.var1 # "123456"
 p MyClass.var2 # nil

Is there any way to initialize var2?

2 Answers 2

6

You could do this if var2 is not a boolean.

class MyClass
  class << self
    attr_writer :var2
  end

  def self.var2
    @@var2 ||= 'my init value'
  end
end
Sign up to request clarification or add additional context in comments.

2 Comments

In this case it's better to use self.var2 and self.var2=(a), isn't it? Thus, attr_accessor :var2 is irrelevant.
Tried using MyClass.var2="a" but then when I puts MyClass.var2, it prints "my init value"
1

First of all, here's a confusion in class variable and singleton class. When you're doing class << self it doesn't mean you can now get @@var1 as self.var1. I illustrate it by this example

class MyClass

  @@var1 = '123456'

  class << self
    attr_accessor :var1

    def get_var1
      @@var1
    end

    def set_var1
      self.var1 = '654321'
    end
  end
end

MyClass.get_var1 #=> '123456'
MyClass.set_var1 #=> '654321'
MyClass.get_var1 #=> '123456'

As you can see @@var1 is available in the whole class scope but it differs from singleton variable.

A class variable is shared among all objects of a class, and it is also accessible to the class methods. So you can initialize it in any place you find it acceptable. The most simple and understandable is right in the class scope.

class MyClass
  @@var1 = '123456'
  ...
end

1 Comment

This is not an answer. I already did it. What is the difference between mine example and your one?

Your Answer

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