Ruby Classes

Keep state in an instance variable and read it with attr_reader.

Ruby
class Counter
  attr_reader :value

  def initialize
    @value = 0
  end

  def increment
    @value += 1
  end
end

counter = Counter.new
counter.increment
counter.increment
puts counter.value
Output
2

Explanation

A Ruby class defines the behavior of its objects. initialize runs when you call Counter.new, and instance variables that start with @ belong to one object.

attr_reader :value generates a method that returns @value, so outside code can read the value but not assign it. Calling counter.increment twice raises @value from 0 to 2.

Explore the dry run
Guided walkthroughReady
1class Counter
2 attr_reader :value
3
4 def initialize
5 @value = 0
6 end
7
8 def increment
9 @value += 1
10 end
11end
12
13counter = Counter.new
14counter.increment
15counter.increment
16puts counter.value

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
Generate a read-only value method.—
—
initialize runs and sets @value to 0.@value = 0
—
The first call makes @value 1.@value = 1
—
Read through attr_reader and print.@value = 1
2

Cost and common mistakes

O(1) per method call.

  • counter.value = 5 raises NoMethodError, because only a reader was defined.
  • A misspelled instance variable such as @valu silently reads as nil.

Try it yourself

Make Counter writable too.

Reveal answer and reasoning

Replace attr_reader with attr_accessor :value so counter.value = 5 works.

Further reading