Exploring OpenStruct and Struct

In Ruby, both OpenStruct and Struct provide ways to create objects with predefined attributes. However, they differ in functionality and flexibility. Let’s explore the differences between OpenStruct and Struct, and showcase examples to illustrate their usage.

OpenStruct

OpenStruct is a flexible data structure that allows the creation of objects with dynamic attributes. It allows you to define attributes on the fly, making it useful when dealing with dynamic or unknown data structures.

1
2
3
4
5
6
person = OpenStruct.new
person.name = "John Doe"
person.age = 30

puts person.name # Output: John Doe
puts person.age  # Output: 30

In this example, we create an OpenStruct object named person and dynamically assign attributes name and age to it.

Struct

Struct on the other hand, is a way to create objects with a fixed set of attributes. It provides a simple and efficient way to define a data structure with predefined attributes.

1
2
3
4
5
Person = Struct.new(:name, :age)
person = Person.new("Jane Smith", 25)

puts person.name # Output: Jane Smith
puts person.age  # Output: 25

In this example, we define a Struct named Person with attributes name and age. We create a new instance of Person and assign values to its attributes.

Differences

Flexibility: OpenStruct allows dynamic attribute assignment, whereas Struct requires predefined attributes during initialization.

Attribute Access: OpenStruct allows attribute access using dot notation, whereas Struct requires accessing attributes using methods generated by the Struct definition.

Performance: Struct is generally more efficient in terms of memory usage and method dispatch since it generates dedicated methods for each attribute.

Remember to consider the dynamic nature of your data when deciding between OpenStruct and Struct. Both options have their strengths and can greatly enhance your Ruby code depending on the use case.