A question about time variable


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
    def create(filename)
        time = Time.now
        @files[filename] = time
        puts "A new file is created"

and this

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

All the method is defined inside of a class.


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

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

Hope the difference is clear! :smiley:


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?


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.


Thank you. It is really helpful.