Structs in Ruby

Our examples will demonstrate how to use struct in the Ruby programming language. Here’s a code example:

# Define a 'Person' struct with fields :name and :age
Person = Struct.new(:name, :age)

# Function to create a new Person struct
def new_person(name)
  p = Person.new(name)
  p.age = 42
  p
end

if __FILE__ == $0
  # This syntax creates a new struct
  puts Person.new("Bob", 20)

  # You can name the fields when initializing a struct
  puts Person.new("Alice", 30)

  # Omitted fields will be nil or the default values
  puts Person.new("Fred")

  # Prefixing with '&' allows access to struct pointers in Ruby (symbolic representation used here)
  # Structs in Ruby are objects, and by default, they behave like pointer semantics
  ann = Person.new("Ann", 40)
  puts ann

  # It's idiomatic to encapsulate new struct creation in constructor functions
  puts new_person("Jon")

  # Access struct fields with a dot
  s = Person.new("Sean", 50)
  puts s.name

  # Structs are mutable in Ruby
  s.age += 1
  puts s.age

  # Using an anonymous struct type for a single value example
  dog = Struct.new(:name, :is_good).new("Rex", true)
  puts dog
end

To run the program, put the code in a .rb file, for example, structs.rb, and use the ruby command.

$ ruby structs.rb

Here’s what you might expect as output:

#<struct Person name="Bob", age=20>
#<struct Person name="Alice", age=30>
#<struct Person name="Fred", age=nil>
#<struct Person name="Ann", age=40>
#<struct Person name="Jon", age=42>
Sean
51
#<struct name="Rex", is_good=true>

Structs in Ruby provide a flexible way to bundle related data and create simple data structures. They are similar to classes but require less boilerplate code. Now that you understand how to use structs in Ruby, you can leverage them to structure your data effectively.