OpenStruct lets you create objects that can have any properties you want, without defining a class first. It makes working with flexible data easy.
0
0
Open struct for dynamic objects in Ruby
Introduction
When you want to quickly create an object with custom properties without writing a full class.
When you receive data with unknown or changing fields and want to access them like object properties.
When you want to group related data together in a simple way for easy access.
When you want to write cleaner code by avoiding hashes with string or symbol keys.
When prototyping or testing and you need flexible objects fast.
Syntax
Ruby
require 'ostruct' obj = OpenStruct.new obj.property = 'value'
You must require 'ostruct' before using OpenStruct.
You can add or change properties anytime by assigning to them.
Examples
Create an empty OpenStruct and add properties one by one.
Ruby
require 'ostruct' person = OpenStruct.new person.name = 'Alice' person.age = 30
Create an OpenStruct with initial properties using a hash.
Ruby
require 'ostruct' person = OpenStruct.new(name: 'Bob', age: 25)
You can add new properties later even if you started with some.
Ruby
require 'ostruct' person = OpenStruct.new(name: 'Carol') person.city = 'New York'
Sample Program
This program creates a car object with make and model initially, then adds year later. It prints all properties.
Ruby
require 'ostruct' car = OpenStruct.new(make: 'Toyota', model: 'Corolla') car.year = 2020 puts "Car make: #{car.make}" puts "Car model: #{car.model}" puts "Car year: #{car.year}"
OutputSuccess
Important Notes
OpenStruct objects are flexible but slower than regular Ruby objects or hashes.
Use OpenStruct when flexibility is more important than speed.
You can convert OpenStruct to a hash with to_h method.
Summary
OpenStruct lets you create objects with dynamic properties easily.
You can add or change properties anytime without defining a class.
It is great for flexible data but not the fastest option.