Ruby 3 · Blocks, classes and pattern matching

Define a class

A class with an initializer, readers and a method.

class Account
  attr_reader :owner, :balance

  def initialize(owner, balance = 0)
    @owner = owner
    @balance = balance
  end

  def deposit(amount)
    @balance += amount
    self
  end

  def to_s = "#{owner}: #{balance}"
end

puts Account.new("Ada").deposit(50)

Official Ruby 3 documentation

More blocks, classes and pattern matching commands

All blocks, classes and pattern matching commands · Ruby 3 cheatsheet

Was this page helpful?