TExcelTAD
Home › Ruby › Ruby Struct & Data

Ruby Struct & Data

Many classes are just bundles of a few named values: a point with x and y, an address, a row from a CSV file. Writing initialize, attr_accessor, == and to_s for each one is tedious. Ruby offers two shortcuts: Struct (mutable) and Data (immutable, Ruby 3.2+).

Struct

Struct.new generates a whole class from a list of field names:

ruby · try it yourself
Point = Struct.new(:x, :y)

a = Point.new(3, 4)
b = Point.new(3, 4)

p a
p a.x
a.y = 10
p a
p a == b
p a.to_a
p a.to_h
#<struct Point x=3, y=4>
3
#<struct Point x=3, y=10>
false
[3, 10]
{x: 3, y: 10}

A struct gives you, for free:

  • a constructor with positional arguments,
  • getters and setters for every field,
  • value-based == (two structs with equal fields are equal),
  • to_a, to_h, readable inspect, and each over the values.

Keyword arguments and methods

Pass keyword_init: true — or simply call new with keywords (Ruby 3.2+) — and add your own methods in a block:

ruby · try it yourself
Product = Struct.new(:name, :price, :qty) do
  def total = price * qty

  def to_s = "#{name} x#{qty} = #{format('%.2f', total)}"
end

items = [
  Product.new("Tea", 3.5, 2),
  Product.new(name: "Honey", price: 6.25, qty: 1),
]
items.each { |i| puts i }
p items.sum(&:total)
p items.max_by(&:price).name
Tea x2 = 7.00
Honey x1 = 6.25
13.25
"Honey"

Missing and extra arguments

Structs are lenient: missing fields become nil; too many arguments raise an error:

ruby · try it yourself
Pair = Struct.new(:left, :right)
p Pair.new(1)

begin
  Pair.new(1, 2, 3)
rescue ArgumentError => e
  puts e.message
end
#<struct Pair left=1, right=nil>
struct size differs

Data: immutable value objects

Data.define (Ruby 3.2+) is like Struct but immutable — there are no setters — and strict about its arguments. That makes it ideal for values that should never change once created: coordinates, money amounts, configuration, results.

ruby · try it yourself
Coord = Data.define(:lat, :lng)

home = Coord.new(lat: 52.37, lng: 4.89)
work = Coord.new(52.36, 4.90)   # positional also works

p home
p home.lat
p home == Coord.new(lat: 52.37, lng: 4.89)

begin
  home.lat = 0
rescue NoMethodError => e
  puts "No setter: #{e.message}"
end

begin
  Coord.new(lat: 1)
rescue ArgumentError => e
  puts e.message
end
#<data Coord lat=52.37, lng=4.89>
52.37
true
No setter: undefined method 'lat=' for an instance of Coord
missing keyword: :lng

with: copying with changes

To "change" an immutable value, create a modified copy with with:

ruby · try it yourself
Settings = Data.define(:theme, :font_size, :autosave) do
  def self.default = new(theme: "light", font_size: 14, autosave: true)

  def describe = "#{theme} theme, #{font_size}px#{autosave ? ', autosave' : ''}"
end

base = Settings.default
mine = base.with(theme: "dark", font_size: 16)

puts base.describe
puts mine.describe
p base.frozen?
light theme, 14px, autosave
dark theme, 16px, autosave
true

The original object stays exactly as it was.

Destructuring with pattern matching

Both Struct and Data objects work with pattern matching (covered in the Pattern Matching lesson):

ruby · try it yourself
Shape = Data.define(:kind, :size)

def area(shape)
  case shape
  in {kind: :square, size:} then size * size
  in {kind: :circle, size:} then (3.14159 * size**2).round(1)
  end
end

p area(Shape.new(:square, 4))
p area(Shape.new(:circle, 2))
16
12.6

Which should I use?

Struct Data Regular class
Setters yes no (immutable) you decide
Missing arguments become nil ArgumentError you decide
== by value yes yes no (identity) unless you define it
Iteration (each, to_a) yes no no
Best for quick mutable records value objects, results objects with real behaviour and state

Tip: Reach for Data by default for simple records. Immutable values are easier to reason about, safe to share, and can be used as hash keys.

Test yourself

What is the main difference between Struct and Data?

  1. Data is faster
  2. Data objects are immutable
  3. Struct cannot have methods
  4. Data cannot be compared

How do you get a copy of a Data object with one field changed?

  1. obj.dup.field = x
  2. obj.with(field: x)
  3. obj.merge(field: x)
  4. obj.set(field, x)

What happens with Pair = Struct.new(:a, :b); Pair.new(1)?

  1. ArgumentError
  2. b is nil
  3. b is 0
  4. b is 1