Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should @@class_variables be avoided in Ruby?

I know that some say that class variables (e.g. @@class_var) should be avoid in Ruby and should use the an instance variable (e.g. @instance_var) in the class scope instead:

def MyClass
  @@foo = 'bar' # Should not do this.
  @foo = 'bar'  # Should do this.
end

Why is the use of class variables frowned upon in Ruby?

like image 952
ab217 Avatar asked Sep 24 '10 12:09

ab217


People also ask

Are class variables bad Ruby?

Class variables in Ruby have a bad name. It's true, they are considered harmful, borderline evil.

Are instance variables thread safe in Ruby?

Performing writes/reads on class variables in Ruby is not thread safe. Performing writes/reads on instance variables appears to be thread safe.

What is @variable in Ruby?

@variable s are called instance variables in ruby. Which means you can access these variables in ANY METHOD inside the class. [ Across all methods in the class] Variables without the @ symbol are called local variables, which means you can access these local variables within THAT DECLARED METHOD only.

What is Instance_variable_get in Ruby?

Method: Object#instance_variable_getReturns the value of the given instance variable, or nil if the instance variable is not set. The @ part of the variable name should be included for regular instance variables. Throws a NameError exception if the supplied symbol is not valid as an instance variable name.


2 Answers

Class variables are often maligned because of their sometimes confusing behavior regarding inheritance:

class Foo
  @@foo = 42

  def self.foo
    @@foo
  end
end

class Bar < Foo
  @@foo = 23
end

Foo.foo #=> 23
Bar.foo #=> 23

If you use class instance variables instead, you get:

class Foo
  @foo = 42

  def self.foo
    @foo
  end
end

class Bar < Foo
  @foo = 23
end

Foo.foo #=> 42
Bar.foo #=> 23

This is often more useful.

like image 166
sepp2k Avatar answered Nov 23 '22 10:11

sepp2k


Be careful; class @@variables and instance @variables are not the same thing.

Essentially, when you declare a class variable in a base class, it’s shared with all subclasses. Changing its value in a subclass will affect the base class and all of its subclasses all the way down the inheritance tree. This behavior is often exactly what’s desired. But equally often, this behavior is not what was intended by the programmer, and it leads to bugs, especially if the programmer did not originally expect for the class to be subclassed by someone else.

From: http://sporkmonger.com/2007/2/19/instance-variables-class-variables-and-inheritance-in-ruby

like image 40
NullUserException Avatar answered Nov 23 '22 11:11

NullUserException