Menu
Coddy logo textTech

Instance Variables

Part of the Object Oriented Programming section of Coddy's Ruby journey. Lesson 3 of 57.

An instance variable starts with @ and belongs to one object. A value stored in initialize stays available to every method of that object, and each instance has its own copy:

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

  def speak
    "#{@name} says Woof"
  end
end

rex = Dog.new("Rex")
bella = Dog.new("Bella")
puts rex.speak
puts bella.speak

Output:

Rex says Woof
Bella says Woof

Methods can change instance variables, so an object remembers what happened to it. Together, its instance variables are the object's state:

class Counter
  def initialize
    @count = 0
  end

  def increment
    @count += 1
  end

  def report
    "count is #{@count}"
  end
end

clicks = Counter.new
clicks.increment
clicks.increment
puts clicks.report

Output:

count is 2

Instance variables cannot be reached from outside the object. Code outside can only call methods, so a class that wants to share a value defines a method that returns it, a reader:

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

  def name
    @name
  end
end

rex = Dog.new("Rex")
puts rex.name
begin
  rex.age
rescue NoMethodError => e
  puts e.message
end

Output:

Rex
undefined method `age' for an instance of Dog

An instance variable that was never assigned is nil and raises no error, so a misspelled name quietly reads a different, empty variable. instance_variables lists the variables an object really has:

class Lamp
  def initialize
    @on = false
  end

  def status
    @onn.inspect
  end
end

lamp = Lamp.new
puts lamp.status
p lamp.instance_variables

Output:

nil
[:@on]
challenge icon

Challenge

Easy

Complete the class Pet. initialize(name, species, age) stores the three values, birthday adds one year to the age, and describe returns one sentence: a pet named Rex, species dog, age 3 gives Rex is a 3 year old dog.

The supplied code creates a Pet from the first three input lines (name, species, age), calls birthday as many times as the fourth line says and prints describe.

Your code goes in pet.rb. main.rb holds the supplied input/output code and cannot be edited.

Try it yourself

require_relative 'pet'

# Supplied input/output code: keep it as it is
input = []
while (line = gets)
  input << line.chomp
end
pet = Pet.new(input[0], input[1], input[2].to_i)
input[3].to_i.times { pet.birthday }
puts pet.describe
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Online Ruby compiler