New class Data for structs

Ruby 3.2 came with a new class Data to defile structs:

Measure = Data.define(:amount, :unit)
 
# Positional arguments constructor is provided
distance = Measure.new(100, 'km')
#=> #
 
# Keyword arguments constructor is provided
weight = Measure.new(amount: 50, unit: 'kg')
#=> #
 
# Alternative form to construct an object:
speed = Measure[10, 'mPh']
#=> #
 
# Works with keyword arguments, too:
area = Measure[amount: 1.5, unit: 'm^2']
#=> #
 
# Argument accessors are provided:
distance.amount #=> 100
distance.unit #=> "km"

Basically the same as Struct, but remember that Struct has arguments writers.

Leave a Reply

Your email address will not be published. Required fields are marked *