State is the information and data associated with an object at a particular point in time. A ticket’s venue, date, or price distinguishes one object from another instead of forcing every instance to use hard-coded values. section 3.2 section 16.1.4
Ruby objects manage state through instance variables and methods:
- Set or reset values by assigning to instance variables such as @venue or @name. section 3.2
- Read values through methods that return the instance variable’s value. section 3.2.1
- Preserve values between method calls; unlike local variables, instance variables remain associated with their object. section 3.2
- Initialize state automatically by passing arguments to new, which forwards them to initialize. section 3.2.1
Separate state between ticket objects
class Ticket def initialize(venue, date) @venue = venue @date = date end def venue @venue end def date @date end end th = Ticket.new("Town Hall", "2025-11-12") cc = Ticket.new("Convention Center", "2025-12-13") puts th.venue puts cc.date Each ticket retains its own venue and date because each object stores separate instance-variable values. section 3.2.1
State is useful but increases the risk of errors as systems grow. A grading example removes instance variables and initialization, replacing stored letter grades with calculations that return values directly, moving toward pure functions. section 16.1.4
Listing 3.1 An instance variable maintaining its value between method calls
class Person
def set_name(string)
puts "Setting person's name..."
@name = string 1
end
def get_name
puts "Returning the person's name..."
@name
end
end
joe = Person.new
joe.set_name("Joe") 2
puts joe.get_name 3
Trace an instance variable from assignment in set_name to retrieval in get_name across separate method calls. section 3.2






































