Ruby Programming/Reference/Objects/Struct



A structure (Struct) is a:

  • data container, convenient way to bundle a number of attributes together without having to write an explicit class.
  • named collection of data (set of variables) representing a single idea or object.

Inside a 'structure' there is a list of fields - example:

  • Contact: first name, last name, phone, email, birthday.
  • Address: street, city, state, region, postal code, GPS location/coordinates.

Structures are similar to arrays in that they contain multiple data. However, instead of an Index to each piece of data, we have a variable "name". Using the above example:

  • structure (collection of data) = Contact
  • first field in structure 'Contact' is 'first name'

Struct can be used without any additional require statement.

Creating a structure


In Ruby takes a set of field names as arguments and returns a new Class.

Newtype =, :data2)
n =  # => <struct Newtype data1=nil, data2=nil>

Class Struct has a method new like other classes. But that method does not return an instance of Struct but rather a class which is a subclass of class Struct. Example:

pnt =, :y)    # => #<Class:0x143ce50>
pnt.ancestors #=> [#<Class:0x143d6f0>, Struct, Enumerable, Object, Kernel, BasicObject]

Arguments to are names of fields that the generated class will have. These names must be provided as Symbols.

  1. approach / method 1"Point", :x, :y) #=> Struct::Point
origin =,0)  # #<struct Struct::Point x=0, y=0>
  1. approach / method 2
Structure_example =, :field2, :field3)
se ="abc", "xyz", 123)    => #<struct Structure_example filed1="abc", field2="xyz", field3=123>

Struct::new returns a new Class object, which can then be used to create specific instances of the new structure. The number of actual parameters must be less than or equal to the number of attributes defined for this class; unset parameters default to nil. Passing too many parameters will raise an ArgumentError.

Changing structure values

se[:field3] = 456

Printing structure values and members

p se    => #<struct Structure_example filed1="abc", field2="xyz", field3=456>
p se.values    => ["abc", "xyz", 456]
p se.members   => [:field1, :field2, :field3]

Comparing structures

Customer =, :address)
joe1   ="Joe", "adr1")
joe2 ="Joe", "adr1")
jane  ="Jane", "adr2")
joe1 == joe2      #=> true
joe1.eql?(joe2)   #=> true
joe1.equal?(joe2) #=> false
joe1 == jane      #=> false
print joe1[:name], joe1["name"], joe1[0] # same result in each case  -   => "Joe"

Please see the rdoc for Struct. Add any further examples/tutorials here.