Creating Class Variables : Class Variables « Class « Ruby






Creating Class Variables


# create instance variables by prefixing a variable name with @. 
# create class variables by prefixing a variable's name with @@. 
# A class variable is shared by all instances of a class
# Only one copy of a class variable exists for a given class. 
# You have to initialize (declare a value for) a class variable before you use it.


class Animal
  @@number_animals = 0

  def initialize(color)
    @color = color
    @@number_animals += 1
  end

  def get_color
    return @color
  end

  def get_number_animals
    return @@number_animals
  end
end

dog = Animal.new("brown")
cat = Animal.new("striped")
squirrel = Animal.new("gray")

puts "Number of animals is " + squirrel.get_number_animals.to_s

 








Related examples in the same category

1.Class variable and instance variable with the same name
2.Update both instance variable and class variable