Struct class
for managing attributes and their values
to create a simple data class
to create a simple DTO (Data Transfer Object)
defines a set of attributes to hold values, and defines their accessor methods (getters and setters; readers and writers)
Person = Struct.new( :firstname, :lastname, :age )
# creating a new subclass of the class Struct
# this subclass is assigned to the constant Person
# when a class is assigned to a constant, then in general Ruby creates a class with the name of this constant (Person)
# now Person is a class
person = Person.new( 'Tom', 'Sawyer', 11 )
person.firstname # => Tom # getter, reader
person.lastname # => Sawyer
person.age # => 11
person.age = 12 # setter, writer
person.age # => 12
person.inspect # => #<struct firstname="Tom", lastname="Sawyer", age=12>
person.members # => [:firstname, :lastname, :age] # returns it's members (attributes) as an array
person.values # => ["Tom", "Sawyer", 12] # returns the values of it's attributes as an array
person.class # => Person
person.class.superclass # => Struct
Person.superclass # => Struct
Person.class # => Class
Converting a Hash to a Struct
h = { fristname: "Tom", lastname: "Sawyer" }
s = Struct.new( *h.keys ).new( *h.values )