Struct (Ruby)

Struct is a built-in Ruby class that quickly generates a simple class with named attributes, accessors, equality, and a constructor — ideal for lightweight value objects without boilerplate.

Ruby

Struct.new(:x, :y) returns a new class whose instances have x and y accessors, an initializer taking those values, plus sensible ==, to_a, and inspect. It saves you from hand-writing a small class with attr_accessor and initialize for plain data holders.

You can give the generated class methods by passing a block: Struct.new(:w, :h) do def area; w * h; end end. Two Structs with equal attribute values are equal, which makes them handy as hash keys and in tests. Keyword_init: true makes the constructor take named arguments.

Reach for Struct when you need a quick value object with a little behavior. For frozen, keyword-based value objects, Ruby 3.2+ adds Data.define as an immutable sibling; for richer behavior, write a full class.

Syntax

Point = Struct.new(:x, :y)
Point.new(1, 2)

Examples

Ruby

Point = Struct.new(:x, :y) do
  def distance_to_origin
    Math.sqrt(x**2 + y**2)
  end
end

p = Point.new(3, 4)
puts p.x
puts p.distance_to_origin
puts (p == Point.new(3, 4))

Output:

3
5.0
true

Learn it in a lesson

See also

Back to the Dictionary