Ruby 3 cheatsheet

Ruby 3: Blocks, classes and pattern matching

6 common Ruby 3 tasks.

Write a method that takes a block

yield runs the block the caller supplied. Pass data to the block as arguments.

def repeat(times)
  times.times { |i| yield i + 1 }
end

repeat(3) { |n| puts "round #{n}" }

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)

Share behavior with a module

Include a module to add its methods to a class. Including Comparable gives you < > == from <=>.

class Version
  include Comparable
  attr_reader :number

  def initialize(number) = @number = number
  def <=>(other) = number <=> other.number
end

puts Version.new(2) > Version.new(1)

Define simple data classes

Data.define creates immutable value objects (Ruby 3.2+); Struct is the mutable version.

Point = Data.define(:x, :y)
p1 = Point.new(x: 1, y: 2)
p2 = p1.with(y: 5)
puts p1, p2

Match patterns

case/in destructures arrays and hashes and binds variables.

result = { status: "ok", data: { id: 7 } }
case result
in { status: "ok", data: { id: } }
  puts "found #{id}"
in { status: "error" }
  puts "failed"
end

Create a lambda

A lambda is a callable object that checks its arguments.

double = ->(n) { n * 2 }
puts double.call(4)
puts [1, 2, 3].map(&double).inspect

Was this page helpful?