Lesson 15 of 23 · Ruby 4.1 development
Create objects with classes
Initialize instance state and expose behavior through methods.
Development course: behavior may change with future runtime updates.
Learn
A class defines behavior for its instances. Counter.new creates an instance and calls initialize to set its starting state. An instance variable such as @value belongs to one object; separate instances can hold different values.
Instance methods read or change the state of their receiver. attr_reader :value defines a value method that reads @value. It does not create a writer: the example changes state through increment instead.
Example
class Counter
attr_reader :value
def initialize(start = 0)
@value = start
end
def increment
@value = @value + 1
end
end
first = Counter.new
second = Counter.new(10)
first.increment
p first.value
p second.valueExperiment
Predict both values after the calls on different receivers. Add a call to first.increment and check which object changes.
Trace the value before and after reset. Change the starting argument to 8 and investigate whether reset restores that starting value or always uses zero.