Challenge - 5 Problems
OpenStruct Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this OpenStruct code?
Consider this Ruby code using OpenStruct. What will it print?
Ruby
require 'ostruct' person = OpenStruct.new(name: 'Alice', age: 30) puts person.name puts person.age
Attempts:
2 left
💡 Hint
OpenStruct allows you to access keys as methods.
✗ Incorrect
OpenStruct creates an object with attributes from the hash keys. You can call them like methods to get their values.
❓ Predict Output
intermediate2:00remaining
What happens when you add a new attribute dynamically?
What will this Ruby code print?
Ruby
require 'ostruct' obj = OpenStruct.new obj.color = 'red' puts obj.color
Attempts:
2 left
💡 Hint
OpenStruct allows adding new attributes by assignment.
✗ Incorrect
You can add new attributes to an OpenStruct object by assigning to them. Then you can read them back as methods.
🔧 Debug
advanced2:00remaining
Why does this OpenStruct code raise an error?
This code raises an error. What is the cause?
Ruby
require 'ostruct' obj = OpenStruct.new puts obj.size
Attempts:
2 left
💡 Hint
OpenStruct only has methods for keys you set.
✗ Incorrect
Calling a method that was never set as an attribute on OpenStruct returns nil.
❓ Predict Output
advanced2:00remaining
What is the output of nested OpenStruct objects?
What will this Ruby code print?
Ruby
require 'ostruct' address = OpenStruct.new(city: 'Paris', zip: '75000') user = OpenStruct.new(name: 'Bob', address: address) puts user.address.city
Attempts:
2 left
💡 Hint
OpenStruct objects can be nested as attribute values.
✗ Incorrect
The 'address' attribute is itself an OpenStruct, so you can call city on it.
🧠 Conceptual
expert2:00remaining
How does OpenStruct store its data internally?
Which statement best describes how OpenStruct stores its attributes internally?
Attempts:
2 left
💡 Hint
Think about how OpenStruct allows dynamic method calls for keys.
✗ Incorrect
OpenStruct keeps a hash of attributes and dynamically defines getter and setter methods for each key.