Search code examples
rubyvariablesinstance-variablesclass-instance-variables

What's the difference between defining class instance variable in a class and a method. Why?


Well, like the title shown, what's the difference between the two class instance variables below

class Document
  @default_font = :Arial
  ...
end

And

class Document
  def foo
    @default_font = :Arial
  end
  ...
end

Is there anyone can explain it to me. Thank you very much.


Solution

  • In your first case, the variable is neither a class variable(which should have started with @@, nor an instance variable. It is simply a local variable not available outside the current scope, not even within the instance methods.

    The second is an instance variable.

    class Document
      attr_accessor :var1, :var2
      @var1 = 1
      puts @var1 + 2
    
      def initialize
        @var2 = 4
        puts @var2**2
        #puts @var1 + 6
      end
    
    end
    
    1.9.2p0 :208 > class Document
    1.9.2p0 :209?>     attr_accessor :var1, :var2
    1.9.2p0 :210?>     @var1 = 1
    1.9.2p0 :211?>     puts @var1 + 2
    1.9.2p0 :212?>   
    1.9.2p0 :213 >       def initialize
    1.9.2p0 :214?>         @var2 = 4
    1.9.2p0 :215?>         puts @var2**2
    1.9.2p0 :216?>         #puts @var1 + 6
    1.9.2p0 :217 >         end
    1.9.2p0 :218?>   
    1.9.2p0 :219 >     end
    3
     => nil 
    1.9.2p0 :220 > d = Document.new
    16
     => #<Document:0x1a2f0c @var2=4> 
    

    The @var1 + 6 inside the instance method gives an error.