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.speakOutput:
Rex says Woof
Bella says WoofMethods 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.reportOutput:
count is 2Instance 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
endOutput:
Rex
undefined method `age' for an instance of DogAn 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_variablesOutput:
nil
[:@on]Challenge
EasyComplete 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Classes and Objects
Working With FilesDefining ClassesInstance VariablesMethods and selfto_s and inspectRecap - Library Card7Polymorphism and Duck Typing
PolymorphismDuck TypingAbstract Methodscase and ClassesRecap - Payment Methods2Accessors and Self
Readers and WritersCustom Settersself in MethodsIdentity and EqualityRecap - Contact List8Special Methods
Equality and hashOperator MethodsIndexing and AppendingCustom CollectionsRecap - Fractions11Project: Library Management
Books and MembersBorrowing Books3Class Methods and Variables
Class MethodsClass Instance VariablesConstantsFactory MethodsRecap - Coupon CodesPractice on your own: Online Ruby compiler