Recall & Review
beginner
What is an OpenStruct in Ruby?
OpenStruct is a Ruby class that allows you to create data objects with arbitrary attributes that can be set and read dynamically, without defining a class beforehand.Click to reveal answer
beginner
How do you create a new OpenStruct object with attributes?
You create it by calling OpenStruct.new and passing a hash of key-value pairs. For example:
person = OpenStruct.new(name: 'Alice', age: 30).Click to reveal answer
beginner
How can you add or change attributes on an existing OpenStruct object?
You can assign new attributes or change existing ones by simple dot notation, like
person.city = 'New York' or person.age = 31.Click to reveal answer
beginner
What happens if you try to access an attribute that was never set on an OpenStruct object?
It returns
nil instead of raising an error, because OpenStruct allows dynamic attributes that may or may not exist.Click to reveal answer
intermediate
Why might you use OpenStruct instead of a regular Ruby class?
OpenStruct is useful when you want a quick, flexible object to hold data without writing a full class. It’s great for prototyping or when attribute names are not known in advance.
Click to reveal answer
How do you create an OpenStruct object with a name attribute set to 'Bob'?
✗ Incorrect
You create an OpenStruct object by calling OpenStruct.new with a hash of attributes.
What will
person.height return if height was never set on an OpenStruct object?✗ Incorrect
Accessing an unset attribute on OpenStruct returns nil instead of an error.
How do you add a new attribute 'city' with value 'Paris' to an existing OpenStruct object named person?
✗ Incorrect
You add or change attributes on OpenStruct objects by simple dot notation.
Which Ruby library must you require to use OpenStruct?
✗ Incorrect
You must require 'ostruct' to use the OpenStruct class.
Why might OpenStruct be less efficient than a regular Ruby class?
✗ Incorrect
OpenStruct uses dynamic method handling which is slower than fixed methods in regular classes.
Explain how OpenStruct allows you to create objects with flexible attributes in Ruby.
Think about how you can add or read properties without a class.
You got /3 concepts.
Describe a situation where using OpenStruct would be more convenient than defining a full Ruby class.
When you want to store data fast without writing extra code.
You got /3 concepts.