typestar

Struct and Data in Ruby

Value classes in one line, mutable or frozen.

Point = Struct.new(:x, :y) do
  def distance_to(other)
    Math.sqrt((x - other.x)**2 + (y - other.y)**2)
  end
end

a = Point.new(0, 0)
b = Point.new(3, 4)
puts b.x
puts a.distance_to(b)

# Data.define builds an immutable value class
Size = Data.define(:width, :height)
s = Size.new(width: 80, height: 24)
puts s.width * s.height

How it works

  1. Struct.new builds a class from field names, block optional.
  2. The block adds real methods like distance_to.
  3. Data.define makes an immutable version with keyword construction.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
322
Tokens
106
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 80 seconds.

Type this snippet

Step 3 of 3 in Nil & idioms, step 24 of 29 in Language basics.

← Previous Next →