Ruby 3.2 Adds a New Data Class
There's something new coming in Ruby 3.2 this Christmas that I can't wait to start using in all my projects:
Ruby 3.1 [sic] adds a new core class called Data to represent simple immutable value objects. The Data class helps define simple classes for value-alike objects that can be extended with custom methods.
While the Data class is not meant to be used directly, it can be used as a base class for creating custom value objects. The Data class is similar to Struct, but the key difference being that it is immutable.
It'd be easy to look at this and conclude that this is just the same Struct we've been using for decades, with the added constraint that it's immutable. On the other hand, that's a pretty important constraint!
But if you read the pull request,
there are some serious quality of life improvements over Struct
, like built-in
translation of positional arguments to keyword arguments, which allows for
easy-to-define default values:
Measure = Data.define(:amount, :unit)
Measure.new(1, 'km') # => OK
Measure.new(amount: 1, unit: 'km') # => OK
Measure = Data.define(:amount, :unit) do
def initialize(amount: 0, unit: 'cm')
super
end
# imagine other elucidative methods here
def metric?
# …
end
end
This is great news for people who go out of their way to separate their code into two categories: units that implement feature logic and things that represent values. The units implementing application behavior have no state and the values they receive and return are nothing but state. Adopting this approach rigorously transformed my programming practice, allowing for clearer thinking and making progress more predictable.
It's exciting to see Ruby core continue to make consistent iterative progress year after year!