What is the struct class in Ruby?

Struct is a collection of attributes with accessor methods.

A Struct class generates a new subclass that contains a set of members and their values without having to write the class explicitly. For each member, a reader and writer method is created that is similar to #attr_accessor.

Vehicle = Struct.new(:make, :model)
puts Vehicle.superclass
puts Vehicle.ancestors

Since Struct is bundled with the Enumerable module, we can take advantage of methods like #filter, #count, #include?, #uniq, #tally, etc.

Example

Vehicle = Struct.new(:make, :model)
puts Vehicle["Dodge", "Hellcat"]
bike = Vehicle.new("Triumph", "Daytona")
puts bike
bike.make = "Yamaha"
bike["model"] = "R1"
puts bike

Structure with name under Struct

We can pass in a class_name argument that will then be scoped under Struct to define the class.

puts Struct.new("Vehicle", :make, :model)
puts Struct::Vehicle.new("BMW", "S1000RR")

Structure with the name of it’s Constant

When the class_name argument is not passed:

  • If it’s assigned to a constant, a class with the name of the constant is created.
  • If it’s not assigned to a constant, an anonymous class is created.
Vehicle = Struct.new(:make, :model)
puts Vehicle.new("BMW", "S1000RR")
puts Struct.new(:make, :model)

Customize

Vehicle = Struct.new(:make, :model, :number_of_wheels) do
def bike?
number_of_wheels == 2
end
end
hellcat = Vehicle.new("Dodge", "Hellcat", 4)
puts hellcat.bike?

Equality

Returns true if other has the same class and values for its members.

Object#== is used for comparison.

Customer = Struct.new(:name, :address, :zip)
joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
smith = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
puts joe == smith

#values method

Returns values of its members as an array.

Customer = Struct.new(:name, :address, :zip)
joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
puts joe.values

#members method

Returns its members as an array.

Customer = Struct.new(:name, :address, :zip)
joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
puts joe.members

#dig method

Extracts the nested value.

Address = Struct.new(:lane, :city, :location_data)
Customer = Struct.new(:name, :address)
address = Address.new("123 Maple", "Anytown NC", { lane: { street: "123 Watson Street" }, zip: 12345 })
joe = Customer.new("Joe Smith", address)
puts joe.dig(:address, :location_data, :lane, :street)

In this post we have checked all the details about ruby’s Struct class and some of its useful methods.

Thanks for reading!😃

Free Resources

Attributions:
  1. undefined by undefined