Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method
Data#to_h
() -> ::Hash[::Symbol, untyped]
to_h → hash
to_h {|name, value| ... } → hash
struct.c
View on GitHub ↗
#define rb_data_to_h rb_struct_to_h
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