Class variables

Class variables are associated to classes instead of instances. They are prefixed with two “at” signs (@@). For example:

  1. class Counter
  2. @@instances = 0
  3. def initialize
  4. @@instances += 1
  5. end
  6. def self.instances
  7. @@instances
  8. end
  9. end
  10. Counter.instances #=> 0
  11. Counter.new
  12. Counter.new
  13. Counter.new
  14. Counter.instances #=> 3

Class variables can be read and written from class methods or instance methods.

Their type is inferred using the global type inference algorithm.

Class variables are inherited by subclasses with this meaning: their type is the same, but each class has a different runtime value. For example:

  1. class Parent
  2. @@numbers = [] of Int32
  3. def self.numbers
  4. @@numbers
  5. end
  6. end
  7. class Child < Parent
  8. end
  9. Parent.numbers # => []
  10. Child.numbers # => []
  11. Parent.numbers << 1
  12. Parent.numbers # => [1]
  13. Child.numbers # => []

Class variables can also be associated to modules and structs. Like above, they are inherited by including/subclassing types.