0
0
Rubyprogramming~15 mins

Open struct for dynamic objects in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Open Struct for Dynamic Objects
📖 Scenario: You are building a simple program to store information about a book using a flexible object. This object should allow you to add new details easily without changing the class structure.
🎯 Goal: Create a dynamic object using OpenStruct to store book details, add a new attribute, and print the final information.
📋 What You'll Learn
Use Ruby's OpenStruct to create a dynamic object
Add initial attributes for title and author
Add a new attribute year after creation
Print the complete book information
💡 Why This Matters
🌍 Real World
OpenStruct is useful when you want to create objects that can change shape easily, like storing user settings or data from APIs without defining a full class.
💼 Career
Many Ruby developers use OpenStruct for quick prototyping and flexible data handling, especially in web development and scripting tasks.
Progress0 / 4 steps
1
Create an OpenStruct object with initial book details
Write code to require the ostruct library and create an OpenStruct object called book with title set to "The Ruby Way" and author set to "Hal Fulton".
Ruby
Need a hint?

Use require 'ostruct' to load the library. Then create book with OpenStruct.new and pass a hash with keys :title and :author.

2
Add a new attribute for the publication year
Add a new attribute called year to the existing book object and set it to 2020.
Ruby
Need a hint?

Use dot notation to add year to book like book.year = 2020.

3
Access and print the book's title and year
Write code to print the book's title and year using puts and string interpolation with book.title and book.year.
Ruby
Need a hint?

Use puts with double quotes and #{} to insert book.title and book.year into the string.

4
Print the complete book object
Write code to print the entire book object using puts book.
Ruby
Need a hint?

Simply use puts book to print all attributes of the OpenStruct object.