A question about time variable


#1



I'm not exactly stuck. I wonder if I define the variable time as instance variable, such @time, and as a local variable, such as time, will give a different result and error?


between this:

class Computer
    @@users = {}
    def initialize(username, password)
        @username = username
        @password = password
        @files = {}
        @@users[username] = password
    end
    
    def create(filename)
        time = Time.now
        @files[filename] = time
        puts "A new file is created"
    end
        
end


and this

    def create(filename)
        @time = Time.now
        @files[filename] = @time
        puts "A new file is created"
    end

All the method is defined inside of a class.


#2

time as a local variable will only exist inside the method create. It will be created whenever create is called, and will be destroyed when create finishes execution. time will NOT be accessible outside the create method.

@time as an instance variable will be associated with an object of the class Computer. It will be created by create method, but it will exist as long as the object exists, since an instance variable is associated with an object. The instance variable can also be shared by other methods of the same class.

# sharing example
class Computer
    def create
        @time = 12345
    end

    def  update
        @time = @time + 1 # updating the same instance variable
    end
end

Hope the difference is clear! :smiley:


#3

It's quite clear. Thanks.
So, if I wanted to add the method 'Update' involving the variable time later, I should use @time instead right?


#4

Yes, whenever you are in need of a variable that has to be used in multiple methods of a class, you should use an instance variable and not a local variable.


#5

Thank you. It is really helpful.
Thanks.