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.valueOutput
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
1
class Counter2
attr_reader :value3
4
def initialize5
@value = 06
end7
8
def increment9
@value += 110
end11
end12
13
counter = Counter.new14
counter.increment15
counter.increment16
puts 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 |
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.