Translate

December 12, 2012

Class Variables on Class, in Ruby


Class variable

You can declare class variables by using @@ for prefix of variable name, for instance: @@common

A class variable is shared among all objects of a class, and it is also accessible to the class methods that we'll describe later. There is only one copy of a particular class variable for a given class
Class variables must be initialized before they are used. Often this initialization is just a simple assignment in the body of the class definition.
Class variables can easily overwrite by subclasses. This is based on Ruby specification; class variables can be shared on its subclass.
Class variables are similar with global variables. They're too hard to handle safely.
Ruby class variables are not really class variables at all, Apparently they are global to the class hierarchy. Changing a value in the subclass impacts the base classes. Generally speaking, globals and global-like things are bad, they are considered harmful

I'll try to explain problems around class variables in Ruby?

Class variable
You can declare class variables by using @@ for prefix of variable name.

class Share
  # Defining class variable on common
  @@common = :apple
   
  def share
    "Hello, you can have #{@@common}"
  end
   
  def common=(thing)
    @@common = thing
  end
end
 
share_1 = Share.new
puts share_1.share #=> "Hello, you can have apple"
 
share_1 = Share.new
# Share#common method replaces class variable @@common.
share_2.common = :mango
 
# ohh, this effects to other instance of class Share.
puts share_2.share #=> "Hello, you can have mango"


class Share
  @@common = :apple
end
 
# Declare new class Share inherits Fruit
class Share < Fruit
  # You can see superclass' class variable.
  puts @@common #=> :apple
 
  # Try to replace in subclass
  @@common = :mango
end
 
class Share
  # Above line effects to its superclass, Share!
  puts @@common #=> :mango
end

Summary:

Class variables are similar with global variables. They're too hard to handle safely.
For usually cases, I can't recommend to use. Ruby class variables are not really class variables at all, Apparently they are global to the class hierarchy. Changing a value in the subclass impacts the base classes. Generally speaking, globals and global-like things are bad, they are considered harmful
Post a Comment