Ruby Data.define: Immutable Value Objects with Data and Comparable
Ruby’s Data class was introduced in Ruby 3.2, offering a convenient way to define value objects. The concept of value objects was popularized by Martin Fowler and Eric Evans through their books and articles. In the real world, we often represent properties like coordinates on a map (x, y) or the speed of a car—using primitives such as integers or strings. While these work, they lack the semantic clarity and behavior of custom types. This is where value objects shine. They encapsulate meaning and behavior around a set of values.
Ruby’s Data class was created to provide a native way to represent such concepts. Struct does fullfil this requirement, except the part of immutability. Ruby Structs are mutable. Some example of use case for value objects are to represent money, email address, co-ordinates, etc.
Lets now explore ruby Data, keeping in my the characteristics of a value object as shared by Marin Fowler. A value object should have:
- No Identity
- Immutable
- Equality by Value
- Small and Simple
- Reusable
Let’s explore how Ruby’s Data class supports these characteristics.
class Data
Data is a core Ruby class, so no external gems are needed.
Here’s a simple example:
| |