Ruby Programming/Reference/Objects/Struct

StructEdit

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 structureEdit

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

Newtype = Struct.new(:data1, :data2)
n = Newtype.new  # => <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 = Struct.new(:x, :y)    # => #<Class:0x143ce50>
pnt.ancestors #=> [#<Class:0x143d6f0>, Struct, Enumerable, Object, Kernel, BasicObject]

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

  1. approach / method 1
Struct.new("Point", :x, :y) #=> Struct::Point
origin = Struct::Point.new(0,0)  # #<struct Struct::Point x=0, y=0>
  1. approach / method 2
Structure_example = Struct.new(:filed1, :field2, :field3)
se = Structure_example.new("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 valuesEdit

se[:field3] = 456

Printing structure values and membersEdit

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

Compring structuresEdit

Customer = Struct.new(:name, :address)
joe1   = Customer.new("Joe", "adr1")
joe2 = Customer.new("Joe", "adr1")
jane  = Customer.new("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.

Last modified on 11 December 2013, at 04:00