Actions
Feature #19001
closedData: Add #to_h symmetric to constructor with keyword args [Follow-on to #16122 Data: simple immutable value object]
Status:
Closed
Assignee:
-
Target version:
-
Description
Extracted a follow-up to #16122 Data: simple immutable value object
Proposal: Add a #to_h
method symmetric to a constructor accepting keyword arguments¶
This allows round-trip between a Hash
and a Value object instance, for example:
Point = Data.define(:x, :y, :z)
points = [
Point.new(x: 1, y: 0, z: 0),
Point.new(x: 0, y: 1, z: 0),
Point.new(x: 0, y: 0, z: 1),
]
hashes = points.map(&:to_h)
points_2 = hashes.map { |h| Point.new(**h) }
points_2 == points
#=> true
Why?¶
Having symmetric operation between #to_h
and a keyword-args constructor is a major ergonomic factor in usage of immutable value objects.
To play with code that works like this, you may take a look at the Values gem
Alternatives¶
If there is no symmetric construction and de-construction along these lines, a number of use cases become more complicated and less ergonomic.
Actions
Like0
Like0Like0Like0Like0