我现在想给一个类添加一个字符串类变量,但 RubyMine 提示我说不要用 class variable
那应该用什么方法实现这个目的呢?
![]() | 1 lightening 2016-11-21 06:07:09 +08:00 如果是常量没问题。如果是变量,为什么不用 instance variable 呢? |
![]() | 2 lightening 2016-11-21 06:13:19 +08:00 先说说你要干什么吧,为什么你觉得自己需要类变量。 |
![]() | 3 starvedcat OP @lightening 是常量,就一个字符串 |
![]() | 4 lightening 2016-11-21 07:15:50 +08:00 ![]() 那习惯上用全大写字母表示。这样 RubyMine 应该也就不会提示了。 |
5 ryanzyy 2016-11-21 07:21:47 +08:00 ![]() 1 )可以使用 class variable 只要你清楚它是怎么运作的 2 )常量大写开头即可,需要写在 class 或 module 层面的 scope 3 )也可以写成: def self.const_str; 'my_string'; end |
![]() | 6 msg7086 2016-11-21 08:44:01 +08:00 Constant 没问题。 Variable 会有大问题。 |
7 warrenoo 2016-11-21 12:36:08 +08:00 首先分析你的使用场景到底要的是常量还是变量。 - 如果是常量, 示例如下 class Example XX = "xxxx".freeze end p Example::XXX - 如果是变量,最好不要显式的使用类变量,比如 @@xxx = "xxxx",示例如下 class Example class << self attr_accessor :str def do_something str = "xxxx" p str end end end 最后,如果这个类有没实例化的需求,以上示例中的 class 完全可以替换成 module 来使用 |
8 warrenoo 2016-11-21 12:37:53 +08:00 代码竟然不能排版。。 |