Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the `@count` an instance variable or class variable in Ruby?

class Counter
   def self.counted_new
      @count = 0 if @count.nil?
      @count += 1
      new
   end

   def self.count
      @count
   end
end

In format, @count looks like a instance variable, but when I load this in "irb"(interface ruby) and type four command code

Counter.counted_new
Counter.count
Counter.counted_new
Counter.count

@count finally became 2! Acting like a class variable

like image 919
Peter Zhu Avatar asked Dec 12 '22 00:12

Peter Zhu


1 Answers

@count is always an instance variable, but it can be an instance variable on a class if it is declared in that context.

In this case, @count is a class instance variable. In other words, by writing @count inside of a class level method you are assigning a variable to that class.

By writing @count inside of a instance method, you are assigning an instance variable that is available in that particular instance only.

If you declare a variable with @@count you get a class variable.

THe main difference between class variables and class instance variables is that class variables are retained in inheritance.

class Foo
  @@klass = "class level variable"
  @klass_instance = "class instance level variable"
end

class Bar < Foo
end


puts Foo.instance_variables.inspect # => [:@klass_instance]
puts Foo.class_variables.inspect  # => [:@@klass]

puts Foo.instance_variable_get(:@klass_instance)
# => "klass instance level variable"
puts Foo.class_variable_get(:@@klass)
# => "class level variable"

# The class variable is inherited, but the class instance variable is not

puts Bar.instance_variables.inspect # => []
puts Bar.class_variables.inspect  # => [:@@klass]

# The @@klass variable is shared between all classes in the downward inheritance chain
# So for example:
Foo.class_variable_set(:@@klass, "foo")
puts Bar.class_variable_get(:@@klass) # => "foo"
like image 117
Jesper Avatar answered Feb 02 '23 00:02

Jesper