A struct can bundle attributes together. If you create a struct, you can set a couple of variables for that struct. Those variables can be of any datatype.

A key difference from an array is that elements of an array are all of the same datatype. That is not the case with a struct.

If you want to combine variables, structs are the way to go. Unlike the concept of object oriented programming, they are just data holders.

Download Free Ruby Ebook

Struct in ruby

Struct example

The ruby example creates a new struct. Then it sets the variables.

1
2
3
4
5
6
7
8
9
10
11

Person = Struct.new(:name, :job) do
def show
puts "My name is #{name} and I'm a #{job}!"
end
end

p1 = Person.new("Albert", "Professor")
puts p1.name
puts p1.job
p1.show

The program bundles the variables (job, name) into a struct named Person.Then that structure can be used to set variables.

In this example the struct has only two variables, but a struct can have as many as you need.

You can create multiple items with the same struct, all with different values. Elements of a struct can be accessed immediately.

Exercises

  1. Create a struct house with variables noRooms, price and city
  2. How does a struct differ from a class?