Ruby
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Methods and Blocks
-
Section 4: Object-Oriented Ruby
-
Section 5: Metaprogramming
-
Section 6: Working with Data and Files
-
Section 7: Ruby Frameworks Overview
-
Section 8: Ecosystem and Testing
-
Section 9: Practical Projects
-
Section 10: Interview Practice
-
Section 11: Data Structures and Algorithms in Ruby
-
Section 12: More Practice Exercises
-
Section 13: Enumerable and Functional Style
-
Section 14: More OOP Practice
-
Section 15: More Testing
-
Section 16: Enumerable and Comparable Modules In Depth
-
Section 17: Ruby Standard Library: Core Utilities
-
Section 18: Ruby Standard Library: Data and Security
-
Section 19: Ruby Standard Library: CLI and Text
-
Section 20: Ruby Networking
-
Section 21: Ruby on Rails Deep Dive
-
Section 22: Ruby Metaprogramming Deep Dive
-
Section 23: Ruby Design Patterns
-
Section 24: Ruby Concurrency
-
Section 25: Ruby Testing Deep Dive
-
Section 26: Ruby Gems and Packaging
-
Section 27: Ruby Performance
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Rails API Development
-
Section 31: Rails Authentication and Authorization
-
Section 32: Rails Testing Deep Dive
-
Section 33: Rails Performance
-
Section 34: Rails Deployment
-
Section 35: Sinatra and Lightweight Ruby Web Apps
-
Section 36: More Ruby Language Deep Dive
-
Section 37: Ruby 3.x Modern Features
-
Section 38: More Data Structures in Ruby
-
Section 39: More Practical Projects
-
Section 40: Ruby Ecosystem Tools
-
Section 41: More Practice and Review
-
Section 42: Final Practice and Mastery
-
Section 43: Ruby Interview Deep Dive
-
Section 44: Ruby Background Processing Deep Dive
-
Section 45: Ruby GraphQL
-
Section 46: Ruby Object Model Deep Dive
-
Section 47: Ruby Hanami Framework Overview
-
Section 48: Ruby gRPC and Protocol Buffers
-
Section 49: Ruby Data Processing
-
Section 50: Ruby Search Integration
-
Section 51: Ruby File Upload and Media
-
Section 52: Ruby Email and Notifications
-
Section 53: Ruby Admin Panels
-
Section 54: Ruby Feature Flags and Experimentation
-
Section 55: Ruby Monitoring and Observability
-
Section 56: Ruby Docker and Deployment Deep Dive
-
Section 57: Ruby Security Deep Dive
-
Section 58: More Advanced Metaprogramming
-
Section 59: More Final Projects
54: Struct and OpenStruct for Lightweight Objects
Why bother with Struct if I can just write a regular class?
I've seen a lot of developers spend way too much time writing "data classes"—classes that don't really have any complex logic and just exist to hold a few pieces of information. You know the drill: you define the class, write out the attr_accessor for every field, and then write an initialize method that just assigns those values to instance variables. It's tedious.
A Struct is essentially a shortcut for that entire pattern. It generates the class, the accessors, and the initializer for you in one line. Take a look at this example for a simple product in an inventory system:
# The tedious way
class Product
attr_accessor :name, :sku, :price
def initialize(name, sku, price)
@name = name
@sku = sku
@price = price
end
end
# The Struct way
Product = Struct.new(:name, :sku, :price)
laptop = Product.new("MacBook Pro", "MBP-14-2023", 1999.99)
puts laptop.name # => "MacBook Pro"
Beyond saving keystrokes, Struct gives you some great defaults. For instance, it overrides the == operator. If you compare two Struct objects with the same values, they'll be equal. If you did that with a standard class, Ruby would just check if they are the exact same object in memory, which usually isn't what you want for data containers.
When should I use OpenStruct instead of a Hash?
I'll be honest: you'll use OpenStruct much less often than Struct, but it has its place. Think of it as a Hash that lets you use dot notation. It's incredibly useful when you're dealing with data that is highly dynamic or when you're mocking objects for tests.
Imagine you're building a configuration loader where the settings might change depending on the environment. Using a Hash is fine, but config[:api_key] is just a bit clunkier than config.api_key.
require 'ostruct'
# Creating a dynamic config object
config = OpenStruct.new(api_key: "secret_123", timeout: 30)
# I can add new attributes on the fly without defining them first
config.retries = 3
puts config.api_key # => "secret_123"
puts config.retries # => 3
If you know exactly what fields your object needs, use a Struct. If you're essentially creating a "bag of properties" that might change during runtime, OpenStruct is your friend.
What's the catch? When are these a bad idea?
Nothing in Ruby is free. The biggest trade-off with OpenStruct is performance. Because it uses method_missing under the hood to handle those dynamic calls, it is significantly slower than a Hash or a Struct. In a tight loop with thousands of iterations, OpenStruct will absolutely kill your performance. I generally avoid it in production code unless the convenience outweighs the cost.
As for Struct, the main "gotcha" is that it's very permissive. All attributes are public and writable by default. If you need strict encapsulation—meaning you want to validate data before it's set or keep certain fields private—you have to go back to a full-blown class.
I usually follow this rule of thumb:
- Need a quick, immutable-ish data container? Struct.
- Need a flexible, "schemaless" object for a config or a mock? OpenStruct.
- Need logic, validation, or private state? Class.
📋 Practical Task
Exercise: Building a Cinema Ticket System
You are building a small system to track movie tickets. Your goal is to use Struct for the fixed data and OpenStruct for the variable metadata.
- Create a
StructnamedTicketwith the following attributes:movie_title,seat_number, andprice. - Instantiate a
Ticketobject for "Inception", seat "A12", priced at 15.00. - Create an
OpenStructobject calledticket_meta. Use it to store any additional, non-standard information about the ticket (e.g.,concessions_preordered: trueorcustomer_loyalty_id: "L-99"). - Write a small piece of code that prints a summary using both objects, for example: "Ticket for Inception (Seat A12) costs $15.00. Loyalty ID: L-99".
There are no comments for now.