Ruby Logo

Ruby OpenStruct Mastery

Learn OpenStruct for flexible data containers with dynamic attributes and object notation.

Home Ruby Ruby OpenStruct Mastery

Ruby OpenStruct Mastery

OpenStruct provides a flexible way to create objects with arbitrary attributes. It's perfect for dynamic data structures, configuration objects, and when you need the flexibility of a hash with the convenience of object notation.

OpenStruct Basics & Creation

OpenStruct: OpenStruct creates objects with arbitrary attributes that can be set and accessed dynamically. It's like a hash but with object notation, perfect for flexible data structures and configuration objects.

Creating OpenStruct Objects

# Require the OpenStruct library
require
'ostruct'

# Create OpenStruct from hash
person = OpenStruct.new(name: "Alice", age: 25, city: "New York")
puts
person.name
# "Alice"
puts
person.age
# 25
puts
person.city
# "New York"

# Create empty OpenStruct and add attributes
config = OpenStruct.new
config.database_url = "postgres://localhost:5432/myapp"
config.api_key = "abc123"
config.debug = true

puts
config.database_url
# "postgres://localhost:5432/myapp"
puts
config.debug
# true

Key Feature: OpenStruct allows you to create objects with arbitrary attributes dynamically, making it perfect for configuration objects, data transformation, and flexible data structures.

Dynamic Attributes & Methods

Adding and Modifying Attributes

# Dynamic attribute assignment
user = OpenStruct.new
user.name = "Bob"
user.email = "bob@example.com"
user.age = 30

# Modify existing attributes
user.age = 31
user.role = "admin"

# Access attributes
puts
user.name
# "Bob"
puts
user.role
# "admin"

# Check if attribute exists
puts
user.respond_to?(:name)
# true
puts
user.respond_to?(:salary)
# false

Nested OpenStruct Objects

# Nested structures
company = OpenStruct.new
company.name = "TechCorp"
company.address = OpenStruct.new
company.address.street = "123 Main St"
company.address.city = "San Francisco"
company.address.zip = "94105"

puts
company.name
# "TechCorp"
puts
company.address.city
# "San Francisco"

# Complex nested data
product = OpenStruct.new(
name: "Laptop",
price: 999.99,
specs: OpenStruct.new(
cpu: "Intel i7",
ram: "16GB",
storage: "512GB SSD"
)
)

puts
product.specs.cpu
# "Intel i7"

OpenStruct Methods & Operations

Built-in OpenStruct Methods

# OpenStruct utility methods
person = OpenStruct.new(name: "Alice", age: 25, city: "NYC")

# Get all attributes as hash
puts
person.to_h
# {:name=>"Alice", :age=>25, :city=>"NYC"}

# Get attribute names
puts
person.each_pair.to_a
# [[:name, "Alice"], [:age, 25], [:city, "NYC"]]

# Delete attributes
person.delete_field(:city)
puts
person.to_h
# {:name=>"Alice", :age=>25}

# Check if attribute exists
puts
person.respond_to?(:name)
# true
puts
person.respond_to?(:city)
# false

Iteration and Enumeration

# Iterating over OpenStruct
config = OpenStruct.new(
database: "postgres",
port: 5432,
debug: true,
timeout: 30
)

# Iterate over key-value pairs
config.each_pair
do
|key, value|
puts "#{key}: #{value}"
end

# Convert to array of pairs
puts
config.each_pair.to_a

# Filter attributes
numeric_config = config.each_pair.select { |k, v| v.is_a?(Numeric) }
puts
numeric_config.to_h
# {:port=>5432, :timeout=>30}

Interactive Practice: OpenStruct

Practice Time: Try these OpenStruct examples and experiment with different dynamic attribute patterns. Understanding OpenStruct will make you a more effective Ruby programmer.

Interactive Code Runner

Ruby Code Editor
Output will appear here when you run the code...

OpenStruct Best Practices

✅ Do This

  • Use OpenStruct for configuration objects
  • Leverage for dynamic data structures
  • Use for API response parsing
  • Apply for flexible data containers
  • Use for prototyping and testing

❌ Avoid This

  • Using OpenStruct for performance-critical code
  • Overusing when structs or classes are more appropriate
  • Forgetting that attributes are mutable
  • Using for complex business logic
  • Ignoring memory overhead

Ruby OpenStruct Mastery Checklist

  • Basic Creation: Create OpenStruct objects from hashes or empty
  • Dynamic Attributes: Add and modify attributes at runtime
  • Nested Structures: Create complex nested OpenStruct objects
  • Utility Methods: Use to_h, delete_field, respond_to?
  • Iteration: Iterate over attributes with each_pair
  • Configuration: Use for flexible configuration objects
  • API Responses: Parse dynamic API response data
  • Performance: Understand when to use vs avoid

Next Steps: Practice with OpenStruct for configuration management, API response parsing, and dynamic data structures. OpenStruct is perfect when you need the flexibility of a hash with the convenience of object notation!

Quick Navigation

Related Topics

Video Tutorial

Watch and learn ruby openstruct mastery

Pro Tip: After reading through the content above, watch this video to reinforce your understanding and see the concepts in action!