Ruby 类变量不好吗? [英] Are Ruby class variables bad?

查看:46
本文介绍了Ruby 类变量不好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我实现一个实例"/单例类型模式时,RubyMine 通知使用类变量被认为是错误的形式.

When I implemented an "instance of"/singleton type pattern, RubyMine notified that using class variables were considered bad form.

我遇到的唯一信息是使用类变量会使继承变得有点松散.以下代码会给我带来问题还有其他原因吗?

The only information I came across is that using class variables can make inheritance a bit squirrelly. Is there any other reason why the following code would give me problems?

class Settings
  private_class_method :new
  attr_accessor :prop1
  attr_accessor :prop2

  @@instance = nil

  def Settings.instance_of
    @@instance = new unless @@instance
    @@instance
  end
  def initialize
    @prop2 = "random"
  end
end

另外,有没有更好的方法,Ruby-wise,来实现相同的目标,以确保只有一个实例?

Also, is there a better way, Ruby-wise, to achieve the same objective to ensure only a single instance?

推荐答案

Ruby 中类变量的问题在于,当您从类继承时,新类不会获得它自己的类变量,但使用从其超类继承的相同变量.

The problem with class variables in Ruby is that when you inherit from a class then the new class does not get a new copy of its own class variable but uses the same one that it inherited from its superclass.

例如:

class Car
  @@default_max_speed = 100
  def self.default_max_speed
    @@default_max_speed
  end
end

class SuperCar < Car
  @@default_max_speed = 200 # and all cars in the world become turbo-charged
end

SuperCar.default_max_speed # returns 200, makes sense!
Car.default_max_speed # returns 200, oops!

推荐的做法是使用类实例变量(记住,类只是 Ruby 中类 Class 的对象).我强烈建议阅读 Eloquent Ruby 的第 14 章作者:Russ Olsen,其中详细介绍了该主题.

The recommended practice is to use class instance variables (remember that classes are simply objects of class Class in Ruby). I highly recommend reading Chapter 14 of Eloquent Ruby by Russ Olsen, which covers this topic in detail.

这篇关于Ruby 类变量不好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆