Ruby: What is a class variable?
Class variable
Class variables are variables prefixed by @@
.
class Shape
@@no_of_shapes = 6
def instance_method_x
puts "No: #{@@no_of_shapes}"
end
class << self
def class_method_x
puts "No: #{@@no_of_shapes}"
end
end
end
They are visible to class methods.
Shape.class_method_x # => No: 6
They are visible to instance methods.
Shape.new.instance_method_x # => No: 6
They cannot be accessed by instance of class.
shape = Shape.new
puts shape.no_of_shapes
#=> class_var.rb:5:in `<main>': undefined method `no_of_shapes' for #<Shape:0x000000011e968498> (NoMethodError)