Variables de Clase en Ruby

Una variable de clase es compartida entre todos los objectos de una clase.

Los nombres de variables de clase comienzan con dos arrobas (ejemplo: @@contador).

Las variables de clase deben ser inicializadas antes de ser utilizadas.

class Vehicle

  def initialize(number_wheels,colour)
    @number_wheels = number_wheels
    @colour = colour
  end


  def to_s
    "Vehicle:\tNumber Wheels:#{@number_wheels}\tColour:#{@colour}"
  end

end


class Car < Vehicle
  @@number_of_cars = 0

  def initialize(number_wheels, colour, number_doors)
    super(number_wheels, colour)
    @number_doors = number_doors
    @@number_of_cars += 1
  end


  def to_s
    super + "\tNumber Doors:#{@number_doors}\tTotal Number of Car Actually:#{@@number_of_cars}"
  end

end

carExample = Car.new(4,"red",5)
puts carExample.to_s    
# Vehicle:	Number Wheels:4	Colour:red	Number Doors:5	Total Number of Car Actually:1

carExample2 = Car.new(4,"grey",5)
puts carExample2.to_s   
# Vehicle:	Number Wheels:4	Colour:grey	Number Doors:5	Total Number of Car Actually:2


puts carExample.to_s    
#Vehicle:	Number Wheels:4	Colour:red	Number Doors:5	Total Number of Car Actually:2