Struct and OpenStruct in Ruby

Cristiano - July 03, 2015

According to the official Ruby documentation, a Struct is

a convenient way to bundle a number of attributes together, using accessor methods, without having to write an explicit class.

Struct is a very quick and cheap way to create Class-like instances on the fly.
We will quickly see some examples, type the following program and execute it:

# struc_start.rb
person = Struct.new :name, :age
p = person.new
p.name = "Cristiano"
p.age = 27
puts "Hy! I am #{p.name}, age #{p.age}"

Output:

$ ruby struc_start.rb
Hello, I am Cristiano, age 27

person will act like a class, you can declare a new instance of it like this
p = person.new
In the above statement p is the instance of person.

We can type less than the previous program by passing arguments in the new method:

p = person.new "Cristiano", 27

Now if we want to have a method in our p variable we can define it in a do endblock:

# struct_about_me.rb
person = Struct.new :name, :age do
  def about_me
    "Hello, I am #{self.name}, age #{self.age}"
  end
end
p = person.new "Cristiano", 27
puts p.about_me

Output:

$ ruby struct_about_me.rb
Hello, I am Cristiano, age 27

Extra Tip

We can type

person = Struct.new :name, :age
p = person.new
p.name = "Cristiano"
p.age = 27

But we can’t type:

p.profession = "Engineer"

because we have not declared profession in the struct. So it throws an error.

To avoid this kind of things, you can use OpenStruct as shown in the program below:

# open_struct.rb
require 'ostruct'
p = OpenStruct.new
p.name = "Cristiano"
p.age = 27
p.profession = "software engineer"
puts "Hello, I am #{p.name}, age #{p.age} and I am a #{p.profession}"

Output:

$ ruby open_struct.rb
Hello, I am Cristiano, age 27 and I am a software engineer

Open Struct is like struct, but it does not have its data structure or attributes predefined.
On the other hand, OpenStruct must be required with the require statement.