Struct
Creating new structures for data
Section titled “Creating new structures for data”Struct defines new classes with the specified attributes and accessor methods.
Person = Struct.new :first_name, :last_nameYou can then instantiate objects and use them:
person = Person.new 'John', 'Doe'# => #<struct Person first_name="John", last_name="Doe">
person.first_name# => "John"
person.last_name# => "Doe"Customizing a structure class
Section titled “Customizing a structure class”Person = Struct.new :name do def greet(someone) "Hello #{someone}! I am #{name}!" endend
Person.new('Alice').greet 'Bob'# => "Hello Bob! I am Alice!"Attribute lookup
Section titled “Attribute lookup”Attributes can be accessed strings and symbols as keys. Numerical indexes also work.
Person = Struct.new :namealice = Person.new 'Alice'
alice['name'] # => "Alice"alice[:name] # => "Alice"alice[0] # => "Alice"Syntax
Section titled “Syntax”- Structure = Struct.new :attribute