Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 134 ยท Collections

Struct and Data

Learn Ruby's Struct and Data.define for small data-carrying classes - positional and keyword arguments, equality, immutability, with, pattern matching, and when to choose each.

Many classes exist only to hold a few named values: a point, a money amount, a row from a file, a result with a status and a message. Writing a full class for each one means an initialize, some attr_readers, ==, hash and to_s. Ruby ships two shortcuts that generate all of that for you: Struct (mutable, since the early days) and Data (immutable, added in Ruby 3.2).

Both create a new class from a list of member names. You get constructors, readers, equality by value, to_a/to_h, readable inspect output, and support for pattern matching. Choosing between them is simple once you see the difference: use Data for values that should never change, and Struct when the object needs to be updated in place.

A first Struct

Ruby Struct basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Struct.new(:x, :y) returns a class, which we store in the constant Point. Instances get a reader and a writer for each member, bracket access by name or position, and value-based ==. This is the same idea as a C# record or a Python namedtuple, except that the Struct is mutable.

Name the class by assigning the result to a constant (Point = Struct.new(...)). Without a name the output prints as an anonymous class, and error messages become hard to read.

Keyword arguments and defaults

Positional arguments are easy to mix up once there are more than two or three members. Struct accepts keyword arguments too, and keyword_init: true makes them mandatory:

Ruby Struct with keyword_init

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Missing members default to nil, so a typo in a value is silent, while a typo in a keyword is an ArgumentError. If you need real defaults, or validation, give the Struct a block with methods inside (next section).

Adding methods

Struct.new takes a block that is evaluated inside the new class, so you can add methods, override to_s, or set defaults:

Ruby A Struct with behavior

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

A bare super inside initialize passes the same arguments along, including the default we just added. The generated class is an ordinary Ruby class, so inheritance, modules and everything else work. You can also subclass: class Point < Struct.new(:x, :y) is the older style, but assigning the result to a constant is cleaner and avoids an extra anonymous class in the ancestors.

Destructuring a Struct

Structs know how to turn into arrays and hashes, so they unpack easily:

Ruby Destructuring and pattern matching with Struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

A Struct supports both array patterns ([x, y], via deconstruct) and hash patterns ({x:, y:}, via deconstruct_keys), which is what makes it so convenient in case/in.

Data: the immutable cousin

Data.define (Ruby 3.2+) creates a class whose instances cannot be changed. There are no writers, the object is frozen, and the constructor insists that every member is supplied. It is the best default for values.

Ruby Data.define basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Equality and hash are generated, so two Coordinates with the same numbers are interchangeable as hash keys and set members. The method with returns a new object with some members replaced, which is how you "update" an immutable value.

Data is strict where Struct is forgiving:

Ruby Data rejects missing members (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first line prints 1.0, then Ruby stops with main.rb:3:in 'Data#initialize': missing keyword: :lng (ArgumentError). A forgotten value can never become a silent nil. Data objects also cannot be assigned to:

Ruby No setters on Data (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

You see 5, then main.rb:4:in '<main>': undefined method 'amount=' for an instance of Money (NoMethodError). The writer simply does not exist.

Methods, defaults and validation in Data

A block adds methods, just as with Struct. To validate or to supply defaults, override initialize and take keyword arguments (positional arguments are converted to keywords before initialize runs):

Ruby Data with methods, defaults and validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Notice that Money.new(501, "usd") works: Ruby maps positional arguments to keywords and calls initialize(amount: 501, currency: "usd"), and our super(...) stores the upcased currency. This pattern gives you a validated, immutable value object in about ten lines.

Pattern matching with Data

Ruby Data in case/in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

On Ruby 4.0.9 a Data object answers to both deconstruct_keys and deconstruct, so array patterns work as well. Prefer the named forms anyway: members are named values, and { width:, height: } still reads correctly if someone adds a member later, while [w, h] breaks. Data still has no to_a, each or [] by index. The pattern Circle[radius:] is a class check plus a hash pattern, so it also protects you against a wrong type.

Struct versus Data

Ruby The differences side by side

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The last lines show the danger of mutable keys: after key.a = 99 its hash code changed, so the lookup misses until rehash. That is one more reason to prefer Data for anything that may be used as a key or put in a set.

Struct Data
Mutable yes, writers generated no, frozen
Missing members become nil ArgumentError
Positional + keyword construction both both
to_a, each, [] by index yes no (use to_h)
Pattern matching array and hash patterns hash patterns (array patterns work on 4.0.9, but prefer hash)
Ruby version all 3.2+

Choosing, and other options

  • Data for values: coordinates, money, events, configuration, return values with several parts. This should be your first choice for new code.
  • Struct when you really need to mutate in place (a counter holder, a small record you fill step by step), or want array-like behavior.
  • Hash when keys are dynamic or the data comes from outside. A Struct or Data fixes its members when you write the code.
  • A plain class when the object has real behavior, identity, or private state; see Classes and Objects.
  • OpenStruct is slower, accepts any attribute and hides typos; it also became a bundled gem in Ruby 3.5/4.0. Avoid it in new code. Set, OpenStruct and Friends shows why.

A Struct or Data class defined inside a method body is created again on every call, which is slow and makes instances from different calls compare as unequal. Define it once, at the top level or inside a module.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement about Data.define(:x, :y) instances is true?

    Data instances are immutable. You build a changed copy with with(x: 5). Missing members raise ArgumentError, and == compares members.
  2. 2. What does Point = Struct.new(:x, :y); Point.new(1) produce?

    Struct fills missing members with nil. Data would raise instead.
  3. 3. Why can a Struct instance be a risky hash key?

    Struct hashes by value. Mutating a member after using it as a key changes the hash code, leaving the entry in the wrong slot.
  4. 4. How do you get a copy of a Data object with one member changed?

    with returns a new Data instance with the given members replaced and leaves the original unchanged.
  5. 5. Which method does the pattern in { width:, height: } call on a Data or Struct object?

    Hash patterns ask the object for its named values through deconstruct_keys, which Struct and Data both define.

Summary

  • Struct.new and Data.define generate small classes with readers, value equality, inspect, to_h and pattern matching.
  • Struct is mutable, fills missing members with nil and behaves like a tiny collection (to_a, each, []).
  • Data is immutable, requires all members, and updates through with.
  • Pass a block to add methods; override initialize and call super for defaults and validation.
  • Prefer Data for values and hash keys, Struct for in-place changes, a plain class when there is real behavior.
  • Define these classes once as constants, not inside methods.

Next: The Enumerable Module