Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Ruby class variables bad?

Tags:

ruby

singleton

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

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

like image 236
randall Avatar asked Nov 17 '15 16:11

randall


People also ask

Are class variables inherited Ruby?

Ruby doesn't have class variables in the sense that, say, Java (where they are called static fields) has them. It doesn't need class variables, because classes are also objects, and so they can have instance variables just like any other object.

What is a class variable Ruby?

Used declare variables within a class. There are two main types: class variables, which have the same value across all class instances (i.e. static variables), and instance variables, which have different values for each object instance.

Does Ruby have static variables?

In Ruby, there are two implementations for the static keyword: Static Variable: A Class can have variables that are common to all instances of the class. Such variables are called static variables. A static variable is implemented in ruby using a class variable.

What is the difference between class variable and instance variable in Ruby?

What is the difference between class variables and class instance variables? The main difference is the behavior concerning inheritance: class variables are shared between a class and all its subclasses, while class instance variables only belong to one specific class.


1 Answers

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.

For example:

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!

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.

like image 180
hp4k Avatar answered Sep 29 '22 11:09

hp4k