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
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
[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.
class << self is outdated notation. Recent Ruby versions have singleton_class and define_singleton_method methods, which are easier to read.