0
0
Rubyprogramming~10 mins

Open struct for dynamic objects in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Open struct for dynamic objects
Create OpenStruct object
Assign dynamic attributes
Access or modify attributes
Use object with flexible properties
End
Create an OpenStruct object, add or change attributes anytime, then use it like a flexible object.
Execution Sample
Ruby
require 'ostruct'
person = OpenStruct.new
person.name = 'Alice'
person.age = 30
puts person.name
puts person.age
Creates a dynamic object 'person', adds name and age, then prints them.
Execution Table
StepActionObject StateOutput
1Create OpenStruct objectperson = #<OpenStruct>
2Assign person.name = 'Alice'person = #<OpenStruct name="Alice">
3Assign person.age = 30person = #<OpenStruct name="Alice", age=30>
4puts person.nameperson = #<OpenStruct name="Alice", age=30>Alice
5puts person.ageperson = #<OpenStruct name="Alice", age=30>30
💡 All attributes assigned and printed; program ends.
Variable Tracker
VariableStartAfter 1After 2Final
person#<OpenStruct>#<OpenStruct name="Alice">#<OpenStruct name="Alice", age=30>#<OpenStruct name="Alice", age=30>
Key Moments - 2 Insights
How can we add new attributes to the OpenStruct object after creation?
You can assign new attributes anytime using dot notation like person.new_attr = value, as shown in steps 2 and 3.
What happens if we try to access an attribute that was never set?
Accessing an unset attribute returns nil without error, because OpenStruct allows dynamic properties.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the state of 'person' after step 2?
A#<OpenStruct name="Alice">
B#<OpenStruct>
C#<OpenStruct age=30>
D#<OpenStruct name="Alice", age=30>
💡 Hint
Check the 'Object State' column in row 2 of the execution_table.
At which step is the 'age' attribute added to 'person'?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look for the assignment of person.age in the 'Action' column.
If we try to access person.height without setting it, what will happen?
ARaises an error
BReturns 0
CReturns nil
DReturns an empty string
💡 Hint
Refer to key_moments about accessing unset attributes.
Concept Snapshot
OpenStruct creates flexible objects.
Assign attributes anytime with dot notation.
Access unset attributes returns nil.
Good for dynamic, simple data containers.
Full Transcript
This example shows how to use Ruby's OpenStruct to create an object that can have attributes added or changed anytime. We start by creating an empty OpenStruct object called person. Then we add a name attribute with 'Alice' and an age attribute with 30. When we print these attributes, we get 'Alice' and '30' as output. OpenStruct lets you add new properties on the fly and access them easily. If you try to read an attribute that was never set, it returns nil instead of causing an error. This makes OpenStruct useful for flexible data objects.