Struct and Data

Struct.new

Struct.new builds a class with the fields named in the call. It is the shortest way to replace a hash of fixed keys with something that has readers, an inspect and an equality rule:

S = Struct.new(:x, :y, keyword_init: true) p S.new(x: 1)

ruby -e 'S = Struct.new(:x, :y, keyword_init: true); p S.new(x: 1)'

#<struct S x=1, y=nil>

A struct is mutable: s.x = 5 works, and s.y answers nil until it is set. The members also come with to_a, to_h, equality and a readable inspect, which is more than a hash gives for free.

Data.define

Data.define is the immutable version added in Ruby 3.2. The constructor takes positionals or keywords and there are no writers:

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

ruby -e 'Point = Data.define(:x, :y); p Point.new(x: 1, y: 2)'

#<data Point x=1, y=2>

Assigning a member raises, and the message says which writer is missing:

ruby -e 'Point = Data.define(:x, :y); Point.new(x: 1, y: 2).x = 3'

-e:1:in '<main>': undefined method 'x=' for an instance of Point (NoMethodError)

A Data value is frozen, compares by value and has a hash that follows it, so it works as a hash key and inside a set without any extra code. That combination is what a value object needs, and it is the reason to prefer it over a struct in new code.

Methods on the value

Both forms take a block for the body, which is where the small methods live. with returns a copy with one field changed, the immutable way to update:

Point = Data.define(:x, :y) do def sum x + y end end p Point.new(x: 1, y: 2).sum p Point.new(x: 1, y: 2).with(y: 3)

ruby -e 'Point = Data.define(:x, :y) do; def sum = x + y; end; p Point.new(x: 1, y: 2).sum; p Point.new(x: 1, y: 2).with(y: 3)'

3
#<data Point x=1, y=3>

A value that needs to change is replaced, not mutated: point = point.with(y: 3). That removes a whole class of bug where two variables point at one object and one of them edits it.

When a hash is enough

A hash is the right tool for data whose keys are only known at runtime: a JSON response, a row from a CSV, an options bag. A struct or a Data value is the right tool when the keys are fixed and the program writes them in code. The tell is a typo: row[:nmae] answers nil and fails later; row.nmae raises at once.

What to watch for

A struct without keyword_init: true accepts positionals and keywords alike, so a mixed call such as S.new(1, y: 2) stores the trailing hash in the second field instead of setting y. Pass the option to make the form strict, or build the class with Data.define and skip the question.

Neither form validates its arguments. A value object that must reject a negative amount or an empty name needs an explicit check, usually in a factory method that the rest of the program calls instead of new.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which call builds an immutable value object in Ruby 3.2 and later?

    Answer

    Data.define

    Data.define gives readers, equality and a hash, with no writers and a frozen instance.

  2. What does this program print? S = Struct.new(:x, :y, keyword_init: true) p S.new(x: 1)

    Answer

    #<struct S x=1, y=nil>

    An unset member is nil, and Struct shows itself as #<struct Name ...>.

  3. What does this program print? Point = Data.define(:x, :y) p Point.new(x: 1, y: 2)

    Answer

    #<data Point x=1, y=2>

    A Data instance has its own inspect form with the class name and the members.

  4. What does this program raise? Point = Data.define(:x, :y) Point.new(x: 1, y: 2).x = 3

    Answer

    NoMethodError, because there is no x= writer

    A Data value has no writers; a changed value comes from with.

  5. What does this program print? Point = Data.define(:x, :y) do def sum x + y end end p Point.new(x: 1, y: 2).with(y: 3)

    Answer

    #<data Point x=1, y=3>

    with returns a copy with one member changed and leaves the original alone.

  6. What does with return on a Data value?

    Answer

    A new value with the named members changed

    The immutable way to update: a value that needs to change is replaced, not mutated.

  7. When is a plain hash the better choice?

    Answer

    When the keys are only known at runtime

    A JSON response, a CSV row or an options bag has keys the program does not write down.

  8. Why does a typo such as row.nmae fail better than row[:nmae]?

    Answer

    The method call raises at once, while the hash lookup answers nil and fails later

    That immediate failure is the reason to name the fields when they are fixed.

  9. What does this program print? S = Struct.new(:x, :y) p S.new(1, y: 2)

    Answer

    #<struct S x=1, y={y: 2}>

    Without keyword_init the trailing keywords become one positional hash, which lands in y.

  10. What does this program print? S = Struct.new(:x, :y, keyword_init: true) p S.new(x: 1).to_h

    Answer

    {x: 1, y: nil}

    to_h gives every member, and an unset one is nil.

Article author: Arthur Isaev