DEV Community

Sandip Mane
Sandip Mane

Posted on

2 3

Struct class in Ruby

Struct is a collection of attributes with accessor methods,
without having to write the class explicitly.

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

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

> Vehicle.ancestors
=> [Vehicle, Struct, Enumerable, Object, Kernel, BasicObject]
Enter fullscreen mode Exit fullscreen mode

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

Example

> Vehicle = Struct.new(:make, :model)

> Vehicle["Dodge", "Hellcat"]
=> #<struct Vehicle make="Dodge", model="Hellcat">

> bike = Vehicle.new("Triumph", "Daytona")
> bike
=> #<struct Vehicle make="Triumph", model="Daytona">

> bike.make = "Yamaha"
> bike["model"] = "R1"
> bike
=> #<struct Vehicle make="Yamaha", model="R1">
Enter fullscreen mode Exit fullscreen mode

Follow the link for complete article https://www.sandipmane.dev/struct-class-in-ruby

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay