3. Instance Variables

Instance variables are variables prefixed with @. Instance variables are variables that have different values for each instance of the class.

For example, in real life, every cat has a different name and is a different breed. Similarly, in classes, each instance of a class will have different values for various attributes.

Instance variables can be used throughout the instance of the class. Local variables (variables without @) can only be used within the method that it was created in:

For example:

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

  # We can use @name in methods outside of the initialize method as well
  def say_name
    puts "My name is #{@name}"
  end

  # This will give us an error!! Local variables can only be used in the method it was declared in!
  def say_age
    puts "My age is #{age}"
  end
end

Now that we know what the initialize method is and what instance variables are, let's fix our program:

class Dog
  def initialize(name, breed)
    @name = name
    @breed = breed
  end
end

# Let's add parameters so that our initialize method works
barnie = Dog.new("Barnie", "Golden Retriever")

puts barnie.inspect

Save the file and run the program:

ruby dog.rb

Now the output should be something like this:

#<Dog:0x000000024f0d60 @name="Barnie", @breed="Golden Retriever">

As you can see, "Barnie" has been stored in @name and "Golden Retriever" has been stored in @breed. These instance variables are now stored inside of this instance of the Dog object. What if we create another Dog object? Let's make the file look like this:

class Dog
  def initialize(name, breed)
    @name = name
    @breed = breed
  end
end

# Let's add parameters so that our initialize method works
barnie = Dog.new("Barnie", "Golden Retriever")

puts barnie.inspect

cynthia = Dog.new("Cynthia", "Bulldog")

puts cynthia.inspect

Now you should see two different instances of the Order object, both with different values for the instance variables:

#<Dog:0x000000024f0d60 @name="Barnie", @breed="Golden Retriever">
#<Dog:0x000000024f0d60 @name="Cynthia", @breed="Bulldog">

As you can see, instance variables (variables prefixed with @) are variables that have different values for every instance of the object.

Assignment