jason chen
jason chen

Reputation: 872

access class variable in ruby

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

Upvotes: 0

Views: 3383

Answers (2)

Érik Desjardins
Érik Desjardins

Reputation: 993

[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.

Upvotes: 2

Max
Max

Reputation: 22315

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.

Upvotes: 7

Related Questions