0
0
Rubyprogramming~5 mins

Open struct for dynamic objects in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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'?
AOpenStruct.set(name: 'Bob')
BOpenStruct.create('name' => 'Bob')
COpenStruct('name' => 'Bob')
DOpenStruct.new(name: 'Bob')
What will person.height return if height was never set on an OpenStruct object?
Anil
B0
CAn error
Dfalse
How do you add a new attribute 'city' with value 'Paris' to an existing OpenStruct object named person?
Aperson.add(:city, 'Paris')
Bperson.city = 'Paris'
Cperson[:city] = 'Paris'
Dperson.set_city('Paris')
Which Ruby library must you require to use OpenStruct?
Arequire 'ostruct'
Brequire 'open_struct'
Crequire 'struct'
Drequire 'dynamic_object'
Why might OpenStruct be less efficient than a regular Ruby class?
ABecause it requires network access
BBecause it compiles code at runtime
CBecause it uses method_missing and dynamic method creation
DBecause it stores data in a database
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.