Ruby PlaygroundRuby Tutorial
UI ThemeDark

Lesson 15 of 23 · Ruby 3.2

Create objects with classes

Initialize instance state and expose behavior through methods.

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.value

Experiment

  • 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.

Explore the official manual

Ruby 3.2.4 · Example

Ready to run

Output

Run the code to see what happens.