Classes and modules

Define classes with initialize and attr_reader, inherit with <, mix in modules, and use Struct.

Runs in Zerethon IDE · Ruby 4.0 Official Ruby documentation ↗
main.rb
module Describable
  def describe
    "#{self.class.name.downcase} with area #{format("%.2f", area)}"
  end
end

class Shape
  include Describable
end

class Rect < Shape
  attr_reader :width, :height

  def initialize(width, height)
    @width = width
    @height = height
  end

  def area
    width * height
  end

  def to_s
    "Rect(#{width}x#{height})"
  end
end

class Circle < Shape
  def initialize(radius)
    @radius = radius
  end

  def area
    Math::PI * @radius**2
  end
end

r = Rect.new(3, 4)
puts r, r.area
[r, Circle.new(1)].each { |shape| puts shape.describe }

Point = Struct.new(:x, :y)
puts Point.new(1, 2).x

Output

Rect(3x4)
12
rect with area 12.00
circle with area 3.14
1
  • initialize runs when you call ClassName.new. Instance variables start with @.
  • attr_reader :width creates a width method; attr_accessor also creates width=.
  • include mixes a module's methods into a class — Ruby's way to share behaviour between unrelated classes.
  • Defining to_s controls how puts and #{...} show the object.