Bird
Raised Fist0
Rubyprogramming~10 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of Ruby's OpenStruct?
easy
A. To improve performance of Ruby programs
B. To create objects with dynamic properties without defining a class
C. To enforce strict typing on object properties
D. To replace arrays with key-value pairs

Solution

  1. Step 1: Understand what OpenStruct does

    OpenStruct allows creating objects where you can add or change properties anytime without predefining a class.
  2. Step 2: Compare options with OpenStruct's purpose

    Options A, C, and D do not describe OpenStruct's main use. It is not about performance, strict typing, or replacing arrays.
  3. Final Answer:

    To create objects with dynamic properties without defining a class -> Option B
  4. Quick Check:

    OpenStruct = dynamic properties [OK]
Hint: OpenStruct = flexible object with changeable properties [OK]
Common Mistakes:
  • Thinking OpenStruct improves speed
  • Confusing OpenStruct with strict typing
  • Assuming OpenStruct replaces arrays
2. Which of the following is the correct way to create an OpenStruct object with a property name set to "Alice"?
easy
A. person = OpenStruct.new(name: "Alice")
B. person = OpenStruct(name = "Alice")
C. person = OpenStruct{name: "Alice"}
D. person = OpenStruct.new("name", "Alice")

Solution

  1. Step 1: Recall OpenStruct initialization syntax

    OpenStruct.new accepts a hash with symbol keys to set initial properties.
  2. Step 2: Check each option's syntax

    person = OpenStruct.new(name: "Alice") uses correct syntax with symbol key and value. person = OpenStruct(name = "Alice") uses wrong method call. person = OpenStruct{name: "Alice"} uses braces instead of parentheses. person = OpenStruct.new("name", "Alice") uses positional arguments which OpenStruct.new does not support.
  3. Final Answer:

    person = OpenStruct.new(name: "Alice") -> Option A
  4. Quick Check:

    OpenStruct.new(symbol: value) [OK]
Hint: Use OpenStruct.new with symbol keys for properties [OK]
Common Mistakes:
  • Using assignment inside parentheses
  • Using braces instead of parentheses
  • Using positional arguments instead of hash
3. What will be the output of the following Ruby code?
require 'ostruct'
person = OpenStruct.new
person.age = 30
puts person.age
medium
A. Error: undefined method 'age='
B. nil
C. 30
D. 0

Solution

  1. Step 1: Understand OpenStruct dynamic property assignment

    OpenStruct allows adding properties dynamically by assignment, so person.age = 30 sets the age property to 30.
  2. Step 2: Output the property value

    Using puts person.age prints the value 30 stored in the age property.
  3. Final Answer:

    30 -> Option C
  4. Quick Check:

    Dynamic property assignment = 30 [OK]
Hint: Assign properties directly, then access them normally [OK]
Common Mistakes:
  • Expecting nil for uninitialized property
  • Thinking dynamic assignment causes error
  • Confusing with normal Struct behavior
4. Identify the error in this code snippet using OpenStruct:
require 'ostruct'
person = OpenStruct.new
person[:name] = "Bob"
puts person.name
medium
A. person.name is undefined because name was never set
B. Missing parentheses in OpenStruct.new
C. Cannot use puts with OpenStruct properties
D. OpenStruct does not support []= for setting properties

Solution

  1. Step 1: Check how properties are set in OpenStruct

    OpenStruct properties are set by dot notation (e.g., person.name = "Bob"), not by bracket notation.
  2. Step 2: Analyze the code behavior

    Using person[:name] = "Bob" tries to use []= method which OpenStruct does not support, causing an error.
  3. Final Answer:

    OpenStruct does not support []= for setting properties -> Option D
  4. Quick Check:

    Use dot notation, not []= [OK]
Hint: Set properties with dot, not brackets [OK]
Common Mistakes:
  • Using []= to set OpenStruct properties
  • Assuming OpenStruct supports hash-like access
  • Ignoring error messages
5. Given a hash data = {name: "Eve", age: 28, city: "NY"}, how can you create an OpenStruct object and then add a new property country with value "USA" dynamically?
hard
A. person = OpenStruct.new(data); person.country = "USA"
B. person = OpenStruct.new; person = data; person.country = "USA"
C. person = OpenStruct.new(data); person[:country] = "USA"
D. person = OpenStruct.new; person.add(:country, "USA")

Solution

  1. Step 1: Initialize OpenStruct with existing hash

    Use OpenStruct.new(data) to create an object with properties from the hash.
  2. Step 2: Add new property dynamically

    Assign new property with dot notation: person.country = "USA".
  3. Step 3: Check incorrect options

    person = OpenStruct.new; person = data; person.country = "USA" overwrites person with hash, losing OpenStruct. person = OpenStruct.new(data); person[:country] = "USA" uses []= which is invalid. person = OpenStruct.new; person.add(:country, "USA") uses a non-existent method add.
  4. Final Answer:

    person = OpenStruct.new(data); person.country = "USA" -> Option A
  5. Quick Check:

    Initialize with hash + dot assign new property [OK]
Hint: Initialize with hash, add properties by dot assignment [OK]
Common Mistakes:
  • Overwriting OpenStruct with hash
  • Using []= to add properties
  • Calling non-existent methods
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard