Ruby Logo

Ruby Structs Mastery

Master Ruby structs for lightweight data containers and quick classes with custom methods.

Home Ruby Ruby Structs Mastery

Ruby Structs Mastery

Structs are lightweight data containers that provide a quick way to create classes with predefined attributes. They're perfect for simple data objects, value objects, and when you need structured data without the overhead of full classes.

Struct Basics & Creation

Structs: Ruby structs are lightweight classes that automatically generate getter and setter methods for specified attributes. They're perfect for simple data containers and value objects.

Creating Structs

# Basic struct creation
Person = Struct.new(:name, :age, :email)

# Creating instances
person1 = Person.new("Alice", 25, "alice@example.com")
person2 = Person.new("Bob", 30, "bob@example.com")

# Accessing attributes
puts
person1.name
# "Alice"
puts
person1.age
# 25
puts
person1.email
# "alice@example.com"

# Modifying attributes
person1.age = 26
puts
person1.age
# 26

Key Benefits: Structs automatically generate getter and setter methods, provide equality comparison, and are more memory-efficient than full classes for simple data containers.

Structs with Custom Methods

Adding Custom Methods to Structs

# Struct with custom methods
Point = Struct.new(:x, :y) do
def distance_from_origin
Math.sqrt(x * x + y * y)
end
def distance_to(other_point)
dx = x - other_point.x
dy = y - other_point.y
Math.sqrt(dx * dx + dy * dy)
end
def to_s
"(#{x}, #{y})"
end
end

# Using the enhanced struct
point1 = Point.new(3, 4)
point2 = Point.new(0, 0)

puts
point1
# (3, 4)
puts
point1.distance_from_origin
# 5.0
puts
point1.distance_to(point2)
# 5.0

Struct with Default Values

# Struct with default values
User = Struct.new(:name, :email, :active) do
def initialize(name, email, active = true)
super(name, email, active)
end
def active?
active
end
def deactivate!
self.active = false
end
end

user1 = User.new("Alice", "alice@example.com")
user2 = User.new("Bob", "bob@example.com", false)

puts
user1.active?
# true
puts
user2.active?
# false
user1.deactivate!
puts
user1.active?
# false

Struct Features & Capabilities

Built-in Struct Features

# Struct equality and comparison
Person = Struct.new(:name, :age)
person1 = Person.new("Alice", 25)
person2 = Person.new("Alice", 25)
person3 = Person.new("Bob", 30)

puts
person1 == person2
# true
puts
person1 == person3
# false

# Struct to array and hash conversion
puts
person1.to_a
# ["Alice", 25]
puts
person1.to_h
# {:name=>"Alice", :age=>25}

# Struct inspection
puts
person1.inspect
# #<struct Person name="Alice", age=25>
puts
person1.members
# [:name, :age]
puts
person1.values
# ["Alice", 25]

Struct Iteration and Enumerable

# Structs are enumerable
Product = Struct.new(:name, :price, :category)
product = Product.new("Laptop", 999.99, "Electronics")

# Iterating over struct values
product.each
do
|value|
puts "Value: #{value}"
end

# Using enumerable methods
puts
product.map(&:to_s)
# ["Laptop", "999.99", "Electronics"]
puts
product.select { |v| v.is_a?(String) }
# ["Laptop", "Electronics"]

Interactive Practice: Structs

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

Interactive Code Runner

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

Struct Best Practices

✅ Do This

  • Use structs for simple data containers
  • Add custom methods with blocks when needed
  • Leverage built-in equality and comparison
  • Use structs for value objects
  • Consider structs for lightweight classes

❌ Avoid This

  • Using structs for complex business logic
  • Overusing structs when classes are more appropriate
  • Forgetting that structs are mutable by default
  • Using structs for inheritance hierarchies
  • Ignoring performance implications

Ruby Structs Mastery Checklist

  • Basic Creation: Create structs with Struct.new and specified attributes
  • Custom Methods: Add methods to structs using blocks
  • Default Values: Implement custom initialize methods for defaults
  • Equality: Understand automatic equality comparison
  • Conversion: Use to_a, to_h, members, and values methods
  • Iteration: Leverage enumerable capabilities
  • Value Objects: Use structs for immutable data containers
  • Performance: Understand memory and performance characteristics

Next Steps: Practice with structs for data containers, value objects, and simple classes. Structs are perfect for lightweight, structured data when you don't need the full power of classes!

Quick Navigation

Related Topics

Video Tutorial

Watch and learn ruby structs mastery

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