Ruby Classes
Keep state in an instance variable and read it with attr_reader.
On this page
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
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.value2
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
class Counter attr_reader :value def initialize @value = 0 end def increment @value += 1 endend counter = Counter.newcounter.incrementcounter.incrementputs counter.valueFollow 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
| Step / line | What happens | State after step | Output 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.