access class variable in ruby

╄→尐↘猪︶ㄣ 提交于 2020-01-06 05:41:30

问题


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:


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.




回答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.



来源:https://stackoverflow.com/questions/10957936/access-class-variable-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!