ruby – 如何访问类变量?
发布时间:2020-12-16 19:22:59 所属栏目:百科 来源:网络整理
导读:class TestController ApplicationController def test @goodbay = TestClass.varible endendclass TestClass @@varible = "var"end 我得到错误 undefined method 'varible' for TestClass:Class 在线@goodbay = TestClass.varible 怎么了? 解决方法 在Ruby
class TestController < ApplicationController def test @goodbay = TestClass.varible end end class TestClass @@varible = "var" end 我得到错误 undefined method 'varible' for TestClass:Class 在线@goodbay = TestClass.varible 怎么了? 解决方法
在Ruby中,必须通过该对象上的方法读取和写入对象的@instance变量(和@@类变量).例如:
class TestClass @@variable = "var" def self.variable # Return the value of this variable @@variable end end p TestClass.variable #=> "var" Ruby有一些内置方法可以为您创建简单的访问器方法.如果要在类上使用实例变量(而不是类变量): class TestClass @variable = "var" class << self attr_accessor :variable end end Ruby on Rails专门为类变量提供a convenience method: class TestClass mattr_accessor :variable end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |