Instance Variables
Learn about instance variables.
We'll cover the following
Now that we’ve learned how the string that we pass to the new
method passes to the new object’s initialize
method, we can start improving initialize
. We want it to do something with the string and actually initialize our new object:
class Person
def initialize(name)
@name = name
end
end
This introduces a new type of variable called an instance variable. The @name
is what we call an instance variable. The @
symbol at the beginning of the variable name is what tells us that @name
is an instance variable.
The body of the initialize
method now does nothing else but assign the value of the local name
variable to the @name
instance variable.
Local scope versus an object’s scope
Remember that each method has its own local scope, which is created when it’s called and populated with local variables from the arguments list. We’ve also learned that this scope is erased when Ruby exits the method body and returns from the method.
Note: Local variables that are visible in one method aren’t visible in other methods. That’s why they’re called local.
Every object also has its own scope.
An object’s scope is populated with instance variables at the moment we assign something to them. They’re also visible everywhere in the object, that is, in every method that the object has.
Remember: Instance variables live in, and are visible everywhere in, the object’s scope.
Think of an object’s scope as its own knowledge, or memories.
Analogy
For example, you know your name, your email address, and your email password. You keep this knowledge around, and you can use it when you do things (such as responding to another person). Likewise, an object keeps its instance variables around as long as the object exists.
Let’s see how that works in practice.
If we create and output an instance of our class Person
, we’ll see that Ruby now prints out the instance variable too:
person = Person.new("Ada")p person
The first line creates a new instance of the Person
class, passing the "Ada"
string and assigning this new object to the person
variable. The second line then prints it out:
#<Person:0x007fd8947aa868 @name="Ada">
Notice that this includes the @name
instance variable with the "Ada"
value. This specific, concrete instance of the Person
class knows their name.
Think of this process as a programmer creating and immediately naming a new person.