Immutable value objects with Data

suggest change

Data (Ruby 3.2+) defines small classes for value objects. A value object is defined by its fields: two points with the same x and y are equal, and you never change one, you make a new one. Data.define gives you the constructor, readers, equality, hashing, inspect, to_h and pattern matching support in one line.

Data is the immutable sibling of Struct. A Data class has no setters, every member is required, and instances are frozen. The examples below were run with Ruby 4.0.

Defining a Data class

Data.define takes the member names and returns a new class. Assign it to a constant to give it a name:

Point = Data.define(:x, :y)

a = Point.new(1, 2)          # positional
b = Point.new(x: 1, y: 2)    # keywords
c = Point[3, 4]              # [] is an alias for new
d = Point[x: 5, y: 6]

p a, b, c, d
puts a
puts a.x + a.y
p Point.members
p a.frozen?
#<data Point x=1, y=2>
#<data Point x=1, y=2>
#<data Point x=3, y=4>
#<data Point x=5, y=6>
#<data Point x=1, y=2>
3
[:x, :y]
true

You can't call Data.new directly (it raises NoMethodError). Data is only a base class for the classes Data.define creates. Member names can be symbols or strings, and they become symbols.

Every member is required

Struct fills missing members with nil. Data raises an error instead, so a half-built value can't exist:

Point = Data.define(:x, :y)

def try
  yield
rescue => e
  puts "#{e.class}: #{e.message}"
end

try { Point.new(1) }
try { Point.new(x: 1) }
try { Point.new(1, 2, 3) }
try { Point.new(x: 1, y: 2, z: 3) }
ArgumentError: missing keyword: :y
ArgumentError: missing keyword: :y
ArgumentError: wrong number of arguments (given 3, expected 0..2)
ArgumentError: unknown keyword: :z

Even the positional call reports a missing keyword. new turns positional arguments into keywords before it calls initialize. This matters when you override initialize (see below).

A class with no members is allowed. All its instances are equal, which makes it handy as a marker value:

Empty = Data.define
p Empty.new
p Empty.new == Empty.new
#<data Empty>
true

Immutability

There are no setter methods, and the object is frozen, so even instance_variable_set fails:

Point = Data.define(:x, :y)
a = Point.new(1, 2)

begin
  a.x = 10
rescue NoMethodError => e
  puts "#{e.class}: #{e.message}"
end

begin
  a.instance_variable_set(:@x, 10)
rescue FrozenError => e
  puts "#{e.class}: #{e.message}"
end
NoMethodError: undefined method 'x=' for an instance of Point
FrozenError: can't modify frozen Point: #<data Point x=1, y=2>

The freeze is shallow. Data freezes the object, not the objects its members point to. A mutable array inside a Data instance can still change:

Order = Data.define(:id, :items)

o = Order.new(id: 1, items: ["apple"])
o.items << "pear"
p o
p o.items.frozen?
#<data Order id=1, items=["apple", "pear"]>
false

To get a truly immutable value, copy and freeze mutable members in initialize:

FrozenOrder = Data.define(:id, :items) do
  def initialize(id:, items:)
    super(id: id, items: items.dup.freeze)
  end
end

src = ["apple"]
f = FrozenOrder.new(1, src)
src << "pear"                 # doesn't affect f, we stored a copy
p f

begin
  f.items << "plum"
rescue FrozenError => e
  puts "#{e.class}: #{e.message}"
end
#<data FrozenOrder id=1, items=["apple"]>
FrozenError: can't modify frozen Array: ["apple"]

For a deep freeze of an existing value, Ractor.make_shareable freezes the object and everything it references. Values made of shareable parts can be sent between Ractors without copying:

Item = Data.define(:name, :tags)

i = Item.new("book", ["a"].freeze)
p Ractor.shareable?(i)          # "book" is not frozen

s = Ractor.make_shareable(i)
p Ractor.shareable?(s), s.name.frozen?
false
true
true

See Immutability and Values and references for more on freezing in general.

Equality and hashing

Two instances are equal when they are of the same class and their members are equal. == compares members with == and eql? compares them with eql?, the same rules Array uses:

Point = Data.define(:x, :y)
Other = Data.define(:x, :y)
a = Point.new(1, 2)

p a == Point.new(1, 2)
p a.equal?(Point.new(1, 2))     # not the same object
p a == Point.new(1.0, 2.0)      # 1 == 1.0
p a.eql?(Point.new(1.0, 2.0))   # but 1 is not eql? to 1.0
p a.hash == Point.new(1, 2).hash
p a == Other.new(1, 2)          # different class
true
false
true
false
true
false

Because hash and eql? are based on the members, Data instances work as hash keys, set elements and with uniq:

Point = Data.define(:x, :y)

visits = Hash.new(0)
[Point.new(0, 0), Point.new(1, 2), Point.new(0, 0)].each { |pt| visits[pt] += 1 }
p visits

p Set[Point.new(1, 2), Point.new(1, 2)].size
p [Point.new(3, 1), Point.new(1, 2), Point.new(3, 1)].uniq
{#<data Point x=0, y=0> => 2, #<data Point x=1, y=2> => 1}
1
[#<data Point x=3, y=1>, #<data Point x=1, y=2>]

With a mutable Struct used as a hash key, changing a field after insertion breaks the lookup. That can't happen with Data.

Adding methods

Pass a block to Data.define to add methods. It's evaluated in the context of the new class, like a class body. Methods that "change" the value return a new instance, usually built with with:

Vec = Data.define(:x, :y) do
  def self.zero = new(0, 0)

  def +(other) = with(x: x + other.x, y: y + other.y)
  def *(k) = with(x: x * k, y: y * k)
  def length = Math.sqrt(x**2 + y**2)
  def to_s = "(#{x}, #{y})"
end

v = Vec.new(3, 4)
puts v + Vec.new(1, 1)
puts v * 2
puts v.length
puts Vec.zero
(4, 5)
(6, 8)
5.0
(0, 0)

You can also subclass the class that Data.define returns. This reads like a regular class definition and works well with modules and constants:

class Temperature < Data.define(:degrees, :scale)
  include Comparable

  def self.celsius(d) = new(d, :c)

  def to_celsius
    return self if scale == :c
    with(degrees: ((degrees - 32) * 5.0 / 9).round(1), scale: :c)
  end

  def <=>(other) = to_celsius.degrees <=> other.to_celsius.degrees
  def to_s = "#{degrees}°#{scale.upcase}"
end

temps = [Temperature.new(100, :f), Temperature.celsius(30), Temperature.new(50, :f)]
puts temps.sort.join(", ")
puts temps.max
p Temperature.ancestors.take(3)
50°F, 30°C, 100°F
100°F
[Temperature, Comparable, #<Class:0x0000025961ee0518>]

The downside is an extra anonymous class in the ancestor chain. The block form avoids it, so prefer the block unless you want the class syntax.

You can override inspect or to_s like in any class:

Point = Data.define(:x, :y) do
  def inspect = "P(#{x}, #{y})"
end
p [Point.new(1, 2)]
[P(1, 2)]

Defaults, validation and coercion: overriding initialize

Data has no option for default values. Instead, override initialize with keyword arguments that have defaults, and call super. A bare super passes the keywords on, with the defaults filled in:

Server = Data.define(:host, :port, :tls) do
  def initialize(host:, port: 443, tls: true)
    super
  end
end

p Server.new("example.com")
p Server.new("localhost", 8080, false)
p Server.new(host: "localhost", tls: false)
#<data Server host="example.com", port=443, tls=true>
#<data Server host="localhost", port=8080, tls=false>
#<data Server host="localhost", port=443, tls=false>

Server.new("example.com") works with positional arguments too: new converts them to host: "example.com" and then your initialize supplies the rest.

The same hook is the place for validation and normalization:

Money = Data.define(:cents, :currency) do
  def initialize(cents:, currency: "USD")
    unless cents.is_a?(Integer)
      raise ArgumentError, "cents must be an Integer, got #{cents.inspect}"
    end
    super(cents:, currency: currency.to_s.upcase)
  end

  def to_s = format("%.2f %s", cents / 100.0, currency)
end

p Money.new(1999, :eur)
puts Money.new(1999)

begin
  Money.new(19.99)
rescue ArgumentError => e
  puts "#{e.class}: #{e.message}"
end
#<data Money cents=1999, currency="EUR">
19.99 USD
ArgumentError: cents must be an Integer, got 19.99

initialize must take keywords. If you write a positional initialize, new still passes it a single hash of keywords and construction fails:

Bad = Data.define(:x, :y) do
  def initialize(x, y) = super(x: x, y: y)
end

begin
  Bad.new(1, 2)
rescue ArgumentError => e
  puts "#{e.class}: #{e.message}"
end
ArgumentError: wrong number of arguments (given 1, expected 2)

For alternative ways to build a value (from a string, from a hash with different keys), add class methods such as def self.parse(str) instead of making initialize accept many shapes.

Copying with changes: with

with returns a copy with some members replaced. The original stays the same. In current Ruby with goes through initialize, so validation and coercion apply to the copy too:

# Money as defined above
m = Money.new(500)
p m.with(currency: :gbp)
p m

begin
  m.with(cents: "a lot")
rescue ArgumentError => e
  puts "#{e.class}: #{e.message}"
end

p m.with.equal?(m)       # no arguments: returns self

begin
  m.with(1000)
rescue ArgumentError => e
  puts "#{e.class}: #{e.message}"
end

begin
  m.with(amount: 1)
rescue ArgumentError => e
  puts "#{e.class}: #{e.message}"
end
#<data Money cents=500, currency="GBP">
#<data Money cents=500, currency="USD">
ArgumentError: cents must be an Integer, got "a lot"
true
ArgumentError: wrong number of arguments (given 1, expected 0)
ArgumentError: unknown keyword: :amount

with accepts only keywords. An unknown member name is an error, so typos don't go unnoticed.

Converting: to_h, deconstruct, JSON

to_h returns the members as a hash. Like Hash#to_h, it takes an optional block to transform each pair:

require "json"

Point = Data.define(:x, :y)
pt = Point.new(1, 2)

p pt.to_h
p pt.to_h { |k, v| [k.to_s, v * 10] }

def show(x:, y:) = "x=#{x} y=#{y}"
puts show(**pt.to_h)

x, y = pt.deconstruct
p [x, y]

json = pt.to_h.to_json
puts json
back = Point.new(**JSON.parse(json, symbolize_names: true))
p back == pt
{x: 1, y: 2}
{"x" => 10, "y" => 20}
x=1 y=2
[1, 2]
{"x":1,"y":2}
true

Data deliberately isn't a collection. It has no each, [], to_a or to_hash, so **pt raises TypeError and x, y = pt assigns the whole object to x. Call to_h or deconstruct explicitly.

Pattern matching

Data defines deconstruct (for array patterns) and deconstruct_keys (for hash patterns), so instances work in case/in without extra code. Small Data classes make good result types:

Ok = Data.define(:value)
Err = Data.define(:code, :message)

def parse_port(str)
  n = Integer(str, exception: false)
  return Err.new(:not_a_number, "#{str.inspect} is not a number") unless n
  return Err.new(:out_of_range, "#{n} is not in 1..65535") unless (1..65535).cover?(n)
  Ok.new(n)
end

%w[8080 http 70000 22].each do |s|
  case parse_port(s)
  in Ok[value] if value < 1024
    puts "#{s}: privileged port #{value}"
  in Ok(value:)
    puts "#{s}: port #{value}"
  in Err(code: :not_a_number, message:)
    puts "#{s}: error: #{message}"
  in Err[code, _]
    puts "#{s}: error #{code}"
  end
end

parse_port("443") => Ok[port]
p port
p((parse_port("x") in Err))
8080: port 8080
http: error: "http" is not a number
70000: error out_of_range
22: privileged port 22
443
true

Ok[value] checks the class with Ok === result and then matches positionally. Err(code: ..., message:) matches by member name. See Pattern matching for the full syntax.

Data or Struct?

Here is the same class as a Struct:

PS = Struct.new(:x, :y)

s = PS.new(1, 2)
s.x = 10                  # setters
p s
p PS.new(1)               # missing members become nil
p PS.new(x: 1, y: 2)      # keywords work too (Ruby 3.2+)
p s.to_a, s[0], s[:y]     # behaves like a collection
#<struct PS x=10, y=2>
#<struct PS x=1, y=nil>
#<struct PS x=1, y=2>
[10, 2]
10
2
Data.define Struct.new
Setters no yes
Instances frozen yes (shallow) no (call freeze yourself)
Missing arguments ArgumentError nil
Positional and keyword new yes yes (3.2+)
each, [], to_a, Enumerable no yes
==, eql?, hash, to_h, pattern matching yes yes
Copy with changes with dup and assign

Use Data for values: coordinates, money, date ranges, configuration, the results of a computation, messages between threads or Ractors, hash keys. Use Struct when you really need mutation or array-like access, for example a record you fill in step by step while parsing, or when you must support Ruby older than 3.2.

When the value needs a lot of behavior, private state, or fields that aren't part of its identity, write a regular class (see Classes) and define ==, eql? and hash yourself.

See also: Creating new structures for data and Customizing a structure class.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents