zeacuss
zeacuss

Reputation: 2623

Ruby newbie, what is the difference between @var and @@var in a class

as the title says,

what is the difference between @var and @@var in a class definition? Also, what is the difference between self.mymethod and mymethod in defining a method?

Upvotes: 0

Views: 609

Answers (3)

Michi
Michi

Reputation: 11

In intuitive terms, instance vars are used to keep track of the state of each object. On the other hand, class variables are used to keep track of the state of all instances of the class. E.g. you might use @@count to keep track of the number of this class' objects that have been instantiated, like so:

class User
  @@count = 0

  attr_reader :name
  def initialize(name)
    @@count += 1
    @name = name
  end
end

User.count gives you the number of users that have been instantiated so far. user = User.new('Peter') increases User.count by one and user.name returns Peter.

Upvotes: 1

Shamith c
Shamith c

Reputation: 3739

self always refers to the current object.Check the following Eg:-

class Test 
  def test  
    puts "At the instance level, self is #{self}"  
  end  
  def self.test  
    puts "At the class level, self is #{self}"  
  end  
end  
Test.test   
 #=> At the class level, self is Test  
Test.new.test   
 #=> At the instance level, self is #<Test:0x28190>  

object variables are so named because they have scope within, and are associated to, the current object.an object variable, is then accessible from any other method inside that object.

Class variables are particularly useful for storing information relevant to all objects of a certain class.

Upvotes: 2

Aliaksei Kliuchnikau
Aliaksei Kliuchnikau

Reputation: 13739

@@var is a class variable, it is shared between class and all instances of this class. You can access this variable from class methods and from instance methods.

class C
  @@a = 1

  def self.m1 # define class method (this is similar to def C.m1, because self will evaluate to C in this context)
    @@a
  end

  def m2 # define instance method
    @@a
  end
end

C.m1 # => 1
C.new.m2 # => 1

@var is a class instance variable. Normally you can get access to this instance variable from the class methods.

class C
  @a = 1

  def self.m1
    @a
  end

  def m2
    # no direct access to @a because in this context @a will refer to regular instance variable, not instance variable of an object that represent class C 
  end
end

C.m1 # => 1

These variables might be confusing and you should always know the context where you define instance variable @... - it might be defined in the instance of an object that represent a class or might be an instance of regular object.

Upvotes: 4

Related Questions