Monday, September 22, 2008

Instance Variable

Java and C++ programmers are used to declaring their variables in a class, and they think they should do the same in Ruby. WRONG!

For example:

class Animal
@age = 0
@name = ""

def initialize(age, name)
@age = age
@name = name
end
end

In this example, two sets of @age, @name are created. When the initialize method is called, self holds an instance of the Animal class. But the code outside of that function are executed as part of the definition of the Animal class. When @age and @name are executed, it refers to the Animal class, not the object instance. Hence @age, @name inside the initialize function are different from the @age, @name on the outside.


J

No comments: