0

Why class variable in ruby does not behave like static variable, how can I access it simply by doing Mytest.value, instead of MyTest.new.value?

class MyTest
  @@value=0

  def value
    @@value
  end
end

puts MyTest.new.value
1
  • 2
    It is best to not use class variables. I've completely removed them from my toolkit. Instead, use instance variables on your class, like Erik shows. If your instances also need access to them, give them methods that delegate to the class. Commented Jun 9, 2012 at 3:35

2 Answers 2

7

You want something like

class MyTest
  @@value = 0
  def self.value
    @@value
  end
end

The self makes it a class method, which the class calls directly.

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

Comments

2

[EDIT] Read comments to know why not doing this.

class MyTest
  @value=0

  class << self
    attr_accessor :value
  end
end

Instead, if you really need to access variable in such ways, I suggest a simple module.

Otherwise, like Joshua Cheek commented on the original post, you should use Instance Variable for your class and have accessors.

3 Comments

While this behaves similarly, there are important differences between class variables and instance variables for class objects (the big one being how they are treated by inheritance). Also, class << self is outdated notation. Recent Ruby versions have singleton_class and define_singleton_method methods, which are easier to read.
You are right, the right way of doing this is well, the answer you just posted.
The term "static" doesn't really apply in Ruby.

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.