Skip to content

End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Data#to_h

to_h → hash
to_h {|name, value| ... } → hash

Returns Hash representation of the data object.

Example
Measure = Data.define(:amount, :unit)
distance = Measure[10, 'km']

distance.to_h
#=> {:amount=>10, :unit=>"km"}

Like Enumerable#to_h, if the block is provided, it is expected to produce key-value pairs to construct a hash:

Example
distance.to_h { |name, val| [name.to_s, val.to_s] }
#=> {"amount"=>"10", "unit"=>"km"}

Note that there is a useful symmetry between to_h and initialize:

Example
distance2 = Measure.new(**distance.to_h)
#=> #<data Measure amount=10, unit="km">
distance2 == distance
#=> true
See also #members #to_s #inspect #with also in 4.1 · 4.0 · 3.4 · 3.3