Ruby · Course navigation

Ruby Classes

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

On this page
Before you start

Ruby methods.

  • Keep state in an instance variable and read it with attr_reader.
  • Predict the sample output and explain the state changes.
  • Complete the practice task and check the boundary cases.

The concept

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.

Code example

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

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
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

Behind the scenes

How Ruby processes this code

Ruby parses and executes the script. Blocks run when their methods invoke them.

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