Ruby - Using class method, class variable, instance variable and instance method

Description

Using class method, class variable, instance variable and instance method

Demo

class MyClass 
    @@classvar = 1000 # w w w.j  av a  2 s  . c o m
    @instvar = 1000 
                          
    def MyClass.classMethod 
        if @instvar == nil then 
            @instvar = 10 
        else 
            @instvar += 10 
        end 
                              
        if @@classvar == nil then 
            @@classvar = 10 
        else 
            @@classvar += 10 
        end             
    end 
                          
    def instanceMethod 
        if @instvar == nil then 
            @instvar = 1 
        else 
            @instvar += 1 
        end 
                              
        if @@classvar == nil then 
            @@classvar = 1 
        else 
            @@classvar += 1 
        end       
    end 
     
    def showVars 
        return "(instance method) @instvar = #{@instvar}, @@classvar = #{@@classvar}" 
    end 
     
    def MyClass.showVars 
        return "(class method) @instvar = #{@instvar}, @@classvar = #{@@classvar}" 
    end 
     
end 
for i in 0..2 do     
   ob = MyClass.new 
   MyClass.classMethod 
   ob.instanceMethod 
   puts( MyClass.showVars ) 
   puts( ob.showVars ) 
end

Result

Here, the code declares and initializes a class variable and an instance variable, @@classvar and @instvar, respectively.

Its class method, classMethod, increments both these variables by 10.

Its instance method, instanceMethod, increments both variables by 1.

The code assigned values to both the class variable and the instance variable:

@@classvar = 1000 
@instvar = 1000 

Related Topic