0
0
Rubyprogramming~20 mins

Open struct for dynamic objects in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
OpenStruct Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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
Aname\nage
BError: undefined method 'name'
Cnil\nnil
DAlice\n30
Attempts:
2 left
💡 Hint
OpenStruct allows you to access keys as methods.
Predict Output
intermediate
2: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
Ared
Bcolor
Cnil
DNoMethodError
Attempts:
2 left
💡 Hint
OpenStruct allows adding new attributes by assignment.
🔧 Debug
advanced
2: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
AReturns 0 because OpenStruct is empty
BReturns nil because attribute is missing
CNoMethodError because 'size' is not defined
DSyntaxError due to missing attribute
Attempts:
2 left
💡 Hint
OpenStruct only has methods for keys you set.
Predict Output
advanced
2: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
AParis
Bcity
Cnil
DNoMethodError
Attempts:
2 left
💡 Hint
OpenStruct objects can be nested as attribute values.
🧠 Conceptual
expert
2:00remaining
How does OpenStruct store its data internally?
Which statement best describes how OpenStruct stores its attributes internally?
AIt uses a database to store attributes persistently.
BIt stores attributes as instance variables with fixed names.
CIt stores attributes in a hash and defines methods dynamically for each key.
DIt stores attributes in an array indexed by insertion order.
Attempts:
2 left
💡 Hint
Think about how OpenStruct allows dynamic method calls for keys.