liveBook · Manning

State

As explained in The Well-Grounded Rubyist, Fourth Edition

State is the information and data associated with an object that represents its current properties or condition.

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

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains instance-variable storage, initialization, access methods, persistence, and state removal in favor of pure functions.
Examples
Uses Person and Ticket objects, then contrasts a stateful Grade and ReportCard design with a stateless grading system.
What you can do after
Build it from scratch by defining, initializing, retrieving, modifying, or deliberately removing object state.
How it connects
Connects instance variables, object-oriented programming, initialization, getters, enumerators, iterators, and pure functions.

Also explained in

Compare how 39 books explain state →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.