Method: CTypes::Struct#to_h

Defined in:
lib/ctypes/struct.rb

#to_h(shallow: false) ⇒ Hash Also known as: to_hash

return a Hash representation of the data type

Examples:

deep

include CTypes::Helpers
t = struct do
  attribute :inner, struct(value: uint8)
end
i = t.new
i.inner.value = 5
i.to_h                      # => {inner: {value: 5}}

shallow

include CTypes::Helpers
t = struct do
  attribute :inner, struct(value: uint8)
end
i = t.new
i.inner.value = 5
i.to_h(shallow: true)       # => {inner: #<Class:0x646456 value=5>}

Parameters:

  • shallow (Boolean) (defaults to: false)

    set to true to disable deep traversal

Returns:

  • (Hash)


465
466
467
468
469
470
471
472
473
474
475
# File 'lib/ctypes/struct.rb', line 465

def to_h(shallow: false)
  out = {}
  self.class.fields.each do |field|
    value = send(field)
    unless shallow || value.is_a?(::Array) || !value.respond_to?(:to_h)
      value = value.to_h
    end
    out[field] = value
  end
  out
end